import sum from 'lodash/sum';
import { useEffect, useCallback,useState } from 'react';
import { useFieldArray, useFormContext,Controller } from 'react-hook-form';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import InputAdornment from '@mui/material/InputAdornment';
import { inputBaseClasses } from '@mui/material/InputBase';
import { fCurrency } from '@/utils/format-number';
import Iconify from '@/shared/components/iconify';
import { RHFSelect, RHFTextField,RHFSwitch,RHFUpload,RHFUploadAvatar } from '@/shared/components/hook-form';
import { IInvoiceItem } from '@/shared/types/invoice';
import { IProduct } from '@/shared/types/invoice';
import { useBoolean } from '@/hooks/use-boolean';
import ProductNewForm   from './invoice-new-add-product';
import {getProducts, uploadFile,MAX_FILE_SIZE, ALLOWED_TYPES} from '@/shared/api/invoice';
import { endpoints } from "@/utils/axios";
import { fData } from '@/utils/format-number';
import {IconButton} from "@mui/material";


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

type Props = {
  product?: IProduct[];
};

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


export default function InvoiceNewEditDetails({ product }: Props) {
  const { control, setValue, watch, resetField ,setError, clearErrors,formState: { errors }} = useFormContext();
  const [fileType, setFileType] = useState<string | null>(null);
  const [previewFile, setPreviewFile] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'productLine',
  });

  const values = watch();

  const totalOnRow = values.productLine.map((item: IInvoiceItem) => item.quantity * item.price);

  const subTotal = sum(totalOnRow);

  const totalAmountTaxe = values.taxes ? (subTotal* values.taxes)/100.0 : 0;

  const totalAmount = subTotal + totalAmountTaxe;

  const [products, setProducts] = useState<Product[]>([]);

  const productForm = useBoolean();

  const handleDrop = useCallback(
    async (acceptedFiles: File[]) => {
      const file = acceptedFiles[0];

      if (!file) return;

      try {
        const filename = await uploadFile(file);
        setValue('signatureUrl', filename, { shouldValidate: true });

        const filePreviewUrl = URL.createObjectURL(file);
        setPreviewFile(filePreviewUrl);
        setFileType(file.type);
        setFileName(file.name);
        clearErrors('signatureUrl');
      } catch (error) {
        setError('signatureUrl', {
          type: 'manual',
          message: error instanceof Error ? error.message : 'Une erreur est survenue',
        });
      }
    },
    [setValue, setError, clearErrors, setPreviewFile]
  );


  //---------------------------------------------------------------------------
  const handleRemoveImage = useCallback(() => {
    setPreviewFile(null);
    setValue('signatureUrl', null);
    setFileName(null);
  }, [setValue]);
  const handleRemoveFile = useCallback(() => {
    setValue('signatureUrl', null);
  }, [setValue]);

  const handleTaxChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const inputValue = Number(event.target.value);

      if (!isValidTaxValue(inputValue)) {
        setError('taxes', {
          type: 'manual',
          message: 'Please enter a valid tax (between 0 and 100).',
        });
      } else {
        clearErrors('taxes');
      }
      setValue('taxes', inputValue);
    },
    [setValue, setError, clearErrors]
  );

  const handleAddNewProduct = (newProduct: Product) => {
    setProducts((prevProducts) => [...prevProducts, newProduct]);
  };

  useEffect(() => {
    setValue('totalAmount', totalAmount);
    if(values?.signatureUrlS3) {
      const fileExtension = values.signatureUrlS3.split('.').pop();
      if (fileExtension === 'pdf') {
        setFileType('application/pdf');
      } else if (['png', 'jpg', 'jpeg'].includes(fileExtension || '')) {
        setFileType('image/jpeg');
      }
      setPreviewFile(values?.signatureUrlS3)
    }
  }, [setValue, totalAmount]);

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const data = await getProducts();
        setProducts(data);
      } catch (error) {
        console.error(error);
      }
    };

    fetchProducts();
  }, []);


  const handleAdd = () => {
    append({
      title: '',
      description: '',
      product: { id: '', name: '' },
      quantity: 1,
      price: 0,
      total: 0,
    });
  };

  const handleRemove = (index: number) => {
    remove(index);
  };

  const handleClearProduct = () => {
    resetField('product');
  };

  const handleChangeQuantity = useCallback(
    (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, index: number) => {
      setValue(`productLine[${index}].quantity`, Number(event.target.value));
      console.log('Nouvelle quantité :', Number(event.target.value));
      setValue(
        `productLine[${index}].total`,
        values.productLine.map((item: IInvoiceItem) => item.quantity * item.price)[index]
      );
    },
    [setValue, values.productLine]
  );

  const handleChangePrice = useCallback(
    (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, index: number) => {
      setValue(`productLine[${index}].price`, Number(event.target.value));

      setValue(
        `productLine[${index}].total`,
        values.productLine.map((item: IInvoiceItem) => item.quantity * item.price)[index]
      );
    },
    [setValue, values.productLine]
  );


  const renderTotal = (
    <Stack
      spacing={2}
      alignItems="flex-end"
      sx={{ mt: 3, textAlign: 'right', typography: 'body2' }}
    >
      <Stack direction="row">
        <Box sx={{ color: 'text.secondary' }}>Subtotal</Box>
        <Box sx={{ width: 160, typography: 'subtitle2' }}>{fCurrency(subTotal) || '-'}</Box>
      </Stack>


      <Stack direction="row">
        <Box sx={{ color: 'text.secondary' }}>Taxes ({values.taxes}%)</Box>
        <Box sx={{ width: 160 }}>{fCurrency(totalAmountTaxe) || '-'}</Box>  
      </Stack>

      <Stack direction="row" sx={{ typography: 'subtitle1' }}>
        <Box>Total</Box>
        <Box sx={{ width: 160 }}>{fCurrency(calculateTotalAmount(subTotal,values.taxes)) || '-'}</Box>
      </Stack>
    </Stack>
  );

  const renderFooter = (
    <>
      <Stack spacing={3} sx={{ mt: 3, p: 3, bgcolor: 'background.neutral', borderRadius: 2 }}>
        <Typography variant="h6" sx={{ color: 'text.secondary', mb: 2 }}>Signature</Typography>
        
        {!previewFile && (
          <RHFUpload
            name="signatureUrl"
            maxSize={MAX_FILE_SIZE}
            onDrop={handleDrop}
            onDelete={handleRemoveFile}
            sx={{
              py: 2.5,
              width: '100%',
              height: 'auto',
              borderRadius: 1.5,
            }}
          />
        )}
  
        {previewFile && (
          <Box sx={{ position: 'relative', textAlign: 'center' }}>
            {fileType === 'application/pdf' ? (
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 100 }}>
                <img
                  src="https://upload.wikimedia.org/wikipedia/commons/8/87/PDF_file_icon.svg"
                  alt="Aperçu du PDF"
                  style={{ width: '50px', height: 'auto' }}
                />
              </Box>
            ) : (
              <img
                src={previewFile}
                alt="Prévisualisation de l'image"
                style={{ width: '150px', maxWidth: '100%', height: 'auto', borderRadius: '8px', margin: '12px 0' }}
              />
            )}
             <IconButton
            onClick={handleRemoveImage}
            sx={{
              position: 'absolute',
              top: 0,
              right: 0,
              color: 'grey.500',
              '&:hover': { color: 'error.main' },
            }}
          >
            <Iconify icon="eva:close-fill" />
          </IconButton>
          </Box>
        )}
  
        {fileName && (
          <Typography variant="body2" sx={{ mt: 1, textAlign: 'center' }}>
            {fileName}
          </Typography>
        )}
      </Stack>
  
      <Box sx={{ mt: 3 }}>
        <Typography variant="h6" sx={{ color: 'text.secondary', mb: 2 }}>Notes</Typography>
        <RHFTextField
          name="notes"
          placeholder="We appreciate your business. Should you need us to add extra notes let us know!"
          fullWidth
          multiline
          rows={3}
        />
      </Box>
    </>
  );

  return (
    <>
      <Box sx={{ p: 3 }}>
        <Typography variant="h6" sx={{ color: 'text.disabled', mb: 3, mt:0 }}>
          Details:
        </Typography>

        <Stack divider={<Divider flexItem sx={{ borderStyle: 'dashed' }} />} spacing={3}>
          {fields.map((item, index) => (
            <Stack key={item.id} alignItems="flex-end" spacing={1.5}>
              <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ width: 1 }}>
                <RHFTextField
                  size="small"
                  name={`productLine[${index}].title`}
                  label="Title"
                  InputLabelProps={{ shrink: true }}
                />

                <RHFTextField
                  size="small"
                  name={`productLine[${index}].description`}
                  label="Description"
                  InputLabelProps={{ shrink: true }}
                />

                <Controller
                  name="product"
                  control={control}
                  render={({ field }) => (
                    <RHFSelect
                      
                      fullWidth
                      label="Product"
                      InputLabelProps={{ shrink: true }}
                      {...field}
                      onChange={(event) => {
                        const selectedProduct = products.find((product) => product.id === event.target.value);
                        if (selectedProduct) {
                          setValue(`productLine[${index}].product`, selectedProduct);
                        }
                      }}
                      value={values.productLine[index]?.product?.id || ''}
                    >
                      <MenuItem
                        value=""
                        onClick={handleClearProduct}
                        sx={{ fontStyle: 'italic', color: 'text.secondary' }}
                      >
                        None
                      </MenuItem>

                      <Divider sx={{ borderStyle: 'dashed' }} />
                      {products.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={productForm.onTrue}
                          sx={{ flexShrink: 0 }}
                        >
                          Add Product/Service
                        </Button>
                      </MenuItem>
                    </RHFSelect>
                  )}
                />

{/*--------------------------------------------------------------------------  */}


                <RHFSwitch name={`productLine[${index}].quantity`} label={null} sx={{ m: 0 }} />
                <RHFTextField
                  size="small"
                  type="number"
                  name={`productLine[${index}].quantity`}
                  label="Quantity"
                  placeholder="0"
                  disabled={!values.productLine[index]?.quantity}
                  onChange={(event) => handleChangeQuantity(event, index)}
                  InputLabelProps={{ shrink: true }}
                  sx={{ maxWidth: { md: 96 } }}
                />

                <RHFTextField
                  size="small"
                  type="number"
                  name={`productLine[${index}].price`}
                  label="Price"
                  placeholder="0.00"
                  onChange={(event) => handleChangePrice(event, index)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Box sx={{ typography: 'subtitle2', color: 'text.disabled' }}></Box>
                      </InputAdornment>
                    ),
                  }}
                  sx={{ maxWidth: { md: 96 } }}
                />

                <RHFTextField
                  disabled
                  size="small"
                  type="number"
                  name={`productLine[${index}].total`}
                  label="Total"
                  placeholder="0.00"
                  value={values.productLine[index].total === 0 ? '' : values.productLine[index].total.toFixed(2)}
                  onChange={(event) => handleChangePrice(event, index)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Box sx={{ typography: 'subtitle2', color: 'text.disabled' }}></Box>
                      </InputAdornment>
                    ),
                  }}
                  sx={{
                    maxWidth: { md: 104 },
                    [`& .${inputBaseClasses.input}`]: {
                      textAlign: { md: 'right' },
                    },
                  }}
                />
              </Stack>

              <Button
                size="small"
                color="error"
                startIcon={<Iconify icon="solar:trash-bin-trash-bold" />}
                onClick={() => handleRemove(index)}
              >
                Remove
              </Button>
            </Stack>
          ))}
        </Stack>

        <Divider sx={{ my: 3, borderStyle: 'dashed' }} />

        <Stack
          spacing={3}
          direction={{ xs: 'column', md: 'row' }}
          alignItems={{ xs: 'flex-end', md: 'center' }}
        >
          <Button
            size="small"
            color="primary"
            startIcon={<Iconify icon="mingcute:add-line" />}
            onClick={handleAdd}
            sx={{ flexShrink: 0 }}
          >
            Add Item
          </Button>

          <Stack
            spacing={2}
            justifyContent="flex-end"
            direction={{ xs: 'column', md: 'row' }}
            sx={{ width: 1 }}
          >
            <RHFSwitch name="taxes" label={null} sx={{ m: 0 }} />
            <RHFTextField
              size="small"
              label="Taxes(%)"
              name="taxes"
              type="number"
              disabled={!values.taxes}
              sx={{ maxWidth: { md: 120 } }}
              onChange={handleTaxChange}
              error={Boolean(errors.taxes)}
              helperText={errors.taxes?.message as string || ''}
            />
          </Stack>
        </Stack>
        <ProductNewForm
          open={productForm.value}
          onClose={productForm.onFalse}
          onCreate={handleAddNewProduct}
        />
        {renderTotal}
        {renderFooter}
      </Box>
    </>

  );

}

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

const isValidTaxValue = (value: number): boolean => {
  return value >= 0 && value < 100;
};

const calculateTotalAmount = (subTotal:number, taxes:number):number => {
  const totalAmountTaxe = (subTotal * taxes) / 100.0;
  if (!isValidTaxValue(taxes)) {
    return 0;
  }
  const totalAmount = subTotal + totalAmountTaxe;
  return totalAmount;
};
