import React, { useRef, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { toast } from 'sonner';
import { useFABConfig } from '@/hooks/useFABConfig';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { ProductFormTabbed as ProductForm, ProductFormData } from './partials/ProductFormTabbed';
import { Button } from '@/components/ui/button';

export default function ProductNew() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const formRef = useRef<HTMLFormElement>(null);
  const { setPageHeader, clearPageHeader } = usePageHeader();

  // Hide FAB on new product page
  useFABConfig('none');

  // Create mutation
  const createMutation = useMutation({
    mutationFn: async (data: ProductFormData) => {
      return api.post('/products', data);
    },
    onSuccess: (response: any) => {
      toast.success(__('Product created successfully'));
      queryClient.invalidateQueries({ queryKey: ['products'] });
      
      // Navigate back to products index
      navigate('/products');
    },
    onError: (error: any) => {
      toast.error(error.message || __('Failed to create product'));
    },
  });

  const handleSubmit = async (data: ProductFormData) => {
    await createMutation.mutateAsync(data);
  };

  // Set page header with back button and create button
  useEffect(() => {
    const actions = (
      <div className="flex gap-2">
        <Button size="sm" variant="ghost" onClick={() => navigate('/products')}>
          {__('Back')}
        </Button>
        <Button 
          size="sm" 
          onClick={() => formRef.current?.requestSubmit()}
          disabled={createMutation.isPending}
        >
          {createMutation.isPending ? __('Creating...') : __('Create')}
        </Button>
      </div>
    );
    setPageHeader(__('New Product'), actions);
    return () => clearPageHeader();
  }, [createMutation.isPending, setPageHeader, clearPageHeader, navigate]);

  return (
    <div className="space-y-4">
      <ProductForm
        mode="create"
        onSubmit={handleSubmit}
        formRef={formRef}
        hideSubmitButton={true}
      />
    </div>
  );
}
