import * as Yup from 'yup';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import LoadingButton from '@mui/lab/LoadingButton';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import FormProvider, { RHFTextField,} from '@/shared/components/hook-form';
import { IInvoiceClient } from '@/shared/types/invoice';
import { createInvoiceClient } from '@/shared/api/invoice';
import { useMemo } from 'react';
import Box from '@mui/material/Box';
import RHFAutocomplete from '@/shared/components/hook-form/rhf-autocomplete';
import { countries } from '@/shared/assets/data';




// ----------------------------------------------------------------------

type Props = {
  open: boolean;
  onClose: VoidFunction;
  onCreate: (invoiceClient: IInvoiceClient) => void;
  currentInvoiceClient?: IInvoiceClient;
};


export default function InvoiceClientNewForm({ open, onClose, onCreate,currentInvoiceClient }: Props) {
  const NewInvoiceClientSchema = Yup.object().shape({
    company: Yup.string().required('company is required'),
    emailAddress: Yup.string().required("email is required").email('Email must be a valid email address'),
    phoneNumber: Yup.string().required("phone number is required"),
    country: Yup.string().required("country is required"),
    city: Yup.string().required("city is required"),
    street: Yup.string().required("street is required"),
    apartement: Yup.string().required("apartement is required"),
    postalCode: Yup.string().required("postalCode is required"),


  });

  const defaultValues = useMemo(
    () => ({
      company: currentInvoiceClient?.company || '',
      emailAddress: currentInvoiceClient?.emailAddress || '',
      phoneNumber: currentInvoiceClient?.phoneNumber || '',
      country: currentInvoiceClient?.country || '',
      city: currentInvoiceClient?.city || '',
      street: currentInvoiceClient?.street || '',
      apartement: currentInvoiceClient?.apartement || '',
      postalCode: currentInvoiceClient?.postalCode || '',
    }),
    [currentInvoiceClient]
  );

  const methods = useForm({
    resolver: yupResolver(NewInvoiceClientSchema),
    defaultValues,
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
    reset,
  } = methods;

  const onSubmit = handleSubmit(async (data) => {
    try {
      
      
      onCreate(data);
      onClose();
      reset();
    } catch (error) {
      console.error(error);
      console.log("add new invoice client")
    }
  });

  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={onClose}>
      <FormProvider methods={methods} onSubmit={onSubmit}>
        <DialogTitle>New Client</DialogTitle>

        <DialogContent> 
            <Box
                columnGap={2}
                rowGap={3}
                display="grid"
                gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                md: 'repeat(2, 1fr)',
                }}
            >
                <RHFTextField name="company" label="Company" placeholder='Company Name' sx={{ mt: 1}} />  
                <RHFTextField name="emailAddress" label="Email" placeholder='Email Address' sx={{ mt: 1}} />   
            </Box> 

            <Box
                columnGap={2}
                rowGap={3}
                display="grid"
                gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                md: 'repeat(2, 1fr)',
                }}
            >
                <RHFTextField name="phoneNumber" label="Phone Number" placeholder='Phone Number' sx={{ mt: 1}} /> 
                <RHFAutocomplete
                    name="country"
                    type="country"
                    label="Country"
                    placeholder="Choose a country"
                    fullWidth
                    options={countries.map((option) => option.label)}
                    getOptionLabel={(option) => option}
                /> 
            </Box>  

            <Box
                columnGap={2}
                rowGap={3}
                display="grid"
                gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                md: 'repeat(2, 1fr)',
                }}
            >
                <RHFTextField name="city" label="City" placeholder='City Name' sx={{ mt: 1}} />  
                <RHFTextField name="street" label="Street" placeholder='street' sx={{ mt: 1}} />   
            </Box>

            <Box
                columnGap={2}
                rowGap={3}
                display="grid"
                gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                md: 'repeat(2, 1fr)',
                }}
            >
                <RHFTextField name="apartement" label="Apartement" placeholder='apartement' sx={{ mt: 1}} />  
                <RHFTextField name="postalCode" label="PostalCode" placeholder='Postal Code' sx={{ mt: 1}} />   
            </Box> 


        </DialogContent>

        <DialogActions>
          <Button color="inherit" variant="outlined" onClick={onClose}>
            Cancel
          </Button>
          
          <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
                {!currentInvoiceClient ? 'Create Client' : 'Update Client'}
          </LoadingButton>
        </DialogActions>
      </FormProvider>
    </Dialog>
  );
}
