import { Controller, useFormContext } from 'react-hook-form';
import Stack from '@mui/material/Stack';
import MenuItem from '@mui/material/MenuItem';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import Iconify from '@/shared/components/iconify';
import Button from '@mui/material/Button';
import { RHFSelect, RHFTextField } from '@/shared/components/hook-form';
import currencyData from '@/shared/_mock/_devise/Common-Currency.json';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import { IPaymentMethod } from '@/shared/types/invoice';
import { useBoolean } from '@/hooks/use-boolean';
import  PaymentMethodNewForm  from './invoice-new-add-payment-method';
import React, { useEffect, useState } from 'react';
import { getPaymentModes } from '@/shared/api/invoice';






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

type Props = {
  paymentMethod?: IPaymentMethod[];
  isEdit: boolean;
};

interface PaymentMode {
  id?: string;
  name :string;
};


export default function InvoiceNewEditStatusDate({ paymentMethod,isEdit }: Props) {
  const { control, watch,resetField } = useFormContext();

  const values = watch();
  const currencies: Currency[] = Object.values(currencyData);

  const paymentMethodForm = useBoolean();
  const [paymentModes, setPaymentModes] = useState<PaymentMode[]>([]);

  useEffect(() => {
    const fetchPaymentModes = async () => {
      try {
        const data = await getPaymentModes();
        setPaymentModes(data);
      } catch (error) {
        console.error(error);
      }
    };

    fetchPaymentModes();
  }, []);

  const handleAddNewPaymentMethod = (newPaymentMethod: PaymentMode) => {
    setPaymentModes((prevModes) => [...prevModes, newPaymentMethod]);
  };

  const handleClearPaymentMode = () => {
    resetField('paymentMode');
  };


  return (

<Box sx={{ p: 3 }}>

    <Divider sx={{ my: 3, borderStyle: 'dashed', mt:0,mb:3}}/>
    <Typography variant="h6" sx={{ color: 'text.disabled', mb: 3 }}>
        Setting:
    </Typography>
    <Stack
      spacing={1.5}
      direction={{ xs: 'column', sm: 'row' }}
     
    >
      <RHFTextField
        disabled={isEdit}
        name="invoiceNumber"
        label="Invoice number"
        value={values.invoiceNumber}
      />

      <RHFSelect
        fullWidth
        name="status"
        label="Status"
        InputLabelProps={{ shrink: true }}
        PaperPropsSx={{ textTransform: 'capitalize' }}
      >
        {['paid', 'pending', 'overdue', 'draft'].map((option) => (
          <MenuItem key={option} value={option}>
            {option}
          </MenuItem>
        ))}
      </RHFSelect>

      <Controller
        name="paymentMode"
        control={control}
        render={({ field }) => (
          <RHFSelect
            fullWidth
            label="Payment Mode"
            InputLabelProps={{ shrink: true }}
            PaperPropsSx={{ textTransform: 'capitalize' }}
            {...field}
            onChange={(event) => {
              const selectedPaymentMode = paymentModes.find((mode) => mode.id === event.target.value);
              if (selectedPaymentMode) {
                field.onChange(selectedPaymentMode);
              }
            }}
            value={field.value?.id || ''}
          >
            <MenuItem
              value=""
              onClick={handleClearPaymentMode}
              sx={{ fontStyle: 'italic', color: 'text.secondary' }}
            >
              None
            </MenuItem>

            <Divider sx={{ borderStyle: 'dashed' }} />
            {paymentModes.map((option) => (
              <MenuItem key={option.id} value={option.id}>
                {option.name}
              </MenuItem>
            ))}
            <MenuItem>
              <Button
                size="small"
                color="primary"
                startIcon={<Iconify icon="mingcute:add-line" />}
                onClick={paymentMethodForm.onTrue}
                sx={{ flexShrink: 0 }}
              >
                Add Payment mode
              </Button>
            </MenuItem>
          </RHFSelect>
        )}
      />

    <RHFSelect
      fullWidth
      name="devise"
      label="Currency"
      InputLabelProps={{ shrink: true }}
      PaperPropsSx={{ textTransform: 'capitalize' }}
    >
    {currencies.map((currency) => (
      <MenuItem key={currency.code} value={currency.code}>
        {`${currency.name} (${currency.symbol_native})`}
      </MenuItem>
    ))}
    </RHFSelect>

      

      <Controller
        name="dueDate"
        control={control}
        render={({ field, fieldState: { error } }) => (
          <DatePicker
            label="Due date"
            value={field.value }
            onChange={(newValue) => {
              field.onChange(newValue);
            }}
            slotProps={{
              textField: {
                fullWidth: true,
                error: !!error,
                helperText: error?.message,
              },
            }}
          />
        )}
      />
    </Stack>
    <Divider sx={{ my: 3, borderStyle: 'dashed', mt:4,mb:0}}/>
    <PaymentMethodNewForm
        open={paymentMethodForm.value}
        onClose={paymentMethodForm.onFalse}
        onCreate={handleAddNewPaymentMethod}
    />
  </Box>
  );
}

interface Currency {
  code: string;
  name: string;
  symbol_native: string;
}

