import React, { useRef, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { __ } from '@/lib/i18n';
import { CustomersApi, type CustomerFormData } from '@/lib/api/customers';
import { showErrorToast, showSuccessToast } from '@/lib/errorHandling';
import { useFABConfig } from '@/hooks/useFABConfig';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { CustomerForm } from './CustomerForm';
import { Button } from '@/components/ui/button';

export default function CustomerNew() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const formRef = useRef<HTMLFormElement>(null);
  const { setPageHeader, clearPageHeader } = usePageHeader();
  
  // Hide FAB on new customer page
  useFABConfig('none');
  
  // Create mutation
  const createMutation = useMutation({
    mutationFn: (data: CustomerFormData) => CustomersApi.create(data),
    onSuccess: (customer) => {
      showSuccessToast(__('Customer created successfully'), `${customer.display_name} has been added`);
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      navigate('/customers');
    },
    onError: (error: any) => {
      showErrorToast(error);
    },
  });
  
  const handleSubmit = async (data: CustomerFormData) => {
    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('/customers')}>
          {__('Back')}
        </Button>
        <Button 
          size="sm" 
          onClick={() => formRef.current?.requestSubmit()}
          disabled={createMutation.isPending}
        >
          {createMutation.isPending ? __('Creating...') : __('Create Customer')}
        </Button>
      </div>
    );
    setPageHeader(__('New Customer'), actions);
    return () => clearPageHeader();
  }, [createMutation.isPending, setPageHeader, clearPageHeader, navigate]);
  
  return (
    <div>
      <CustomerForm
        mode="create"
        onSubmit={handleSubmit}
        formRef={formRef}
        hideSubmitButton={true}
      />
    </div>
  );
}
