import React, { useState, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
import { useBoolean } from '@/hooks/use-boolean';
import { useResponsive } from '@/hooks/use-responsive';
import Iconify from '@/shared/components/iconify';
import { AddressListDialog } from '../address';
import InvoiceClientNewForm from './invoice-client-new-add-form';
import { listInvoiceClient, getGroupWithAddress } from '@/shared/api/invoice';
import { getUserByEmail } from '@/shared/api/user';
import { IInvoiceClient } from '@/shared/types/invoice';
import { useInvoiceClient } from '@/hooks/use-invoice.clients';
import { enqueueSnackbar } from '@/components/snackbar';

export default function InvoiceNewEditAddress() {
  const { watch, setValue, formState: { errors } } = useFormContext();
  const mdUp = useResponsive('up', 'md');
  const { invoiceClient } = watch();
  const { clients, isLoading, addClient } = useInvoiceClient();
  const to = useBoolean();
  const invoiceClientForm = useBoolean();

  const [addressBooks, setAddressBooks] = useState<IInvoiceClient[]>([]);
  const [managerInfo, setManagerInfo] = useState<any>(null);
  const [loadingManager, setLoadingManager] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchManagerInfo = async () => {
      setLoadingManager(true);
      setError(null);
      try {
        const userEmail = localStorage.getItem('email');
        const agencyId = localStorage.getItem('selectedAgency'); // Ajout de cette ligne
    
        if (!userEmail) {
          throw new Error('User not authenticated');
        }
    
        const userData = await getUserByEmail(userEmail);
        let managerInfoData;
    
        if (userData.group?.id) {
          const groupData = await getGroupWithAddress(userData.group.id);
          managerInfoData = {
            name: groupData.name,
            email: groupData.email,
            phoneNumber: groupData.phoneNumber,
            address: formatAddress(groupData)
          };
          setValue('agencyId', agencyId); 
        } else {
          managerInfoData = {
            name: `${userData.firstName} ${userData.lastName}`,
            email: userData.email,
            phoneNumber: userData.phoneNumber,
            address: formatAddress(userData.address)
          };
          setValue('agencyId', agencyId); // Modification ici
        }
    
        setManagerInfo(managerInfoData);
        setValue('responsibleId', userData.id);
    
      } catch (error) {
        console.error('Error fetching manager info:', error);
        setError('Failed to load manager information');
      } finally {
        setLoadingManager(false);
      }
    };

    fetchManagerInfo();
  }, []);

  useEffect(() => {
    const getInvoiceClients = async () => {
      try {
        const data = await listInvoiceClient();
        setAddressBooks(data);
      } catch (error) {
        console.error('Error fetching invoice clients:', error);
      }
    };

    getInvoiceClients();
  }, []);

  const handleAddNewInvoiceClient = async (formData: IInvoiceClient) => {
    try {
      const createdClient = await addClient(formData);
      
      if (createdClient) {
        // Mettre à jour le formulaire avec le client créé
        setValue('invoiceClient', createdClient);
        
        // Fermer les dialogues
        invoiceClientForm.onFalse();
        to.onFalse();
        
        // Afficher le message de succès avec la variante success
        enqueueSnackbar('Client added successfully', {
          variant: 'success',
          autoHideDuration: 3000, // 3 secondes
          anchorOrigin: {
            vertical: 'top',
            horizontal: 'right',
          },
        });
      }
    } catch (error) {
      console.error('Error adding client:', error);
      
      // Afficher le message d'erreur avec la variante error
      enqueueSnackbar(
        'Failed to add client', 
        {
          variant: 'error',
          autoHideDuration: 3000,
          anchorOrigin: {
            vertical: 'top',
            horizontal: 'right',
          },
        }
      );
    }
  };

  const formatAddress = (addressData: any) => {
    if (!addressData) return 'Adresse non disponible';
    return `${addressData.primaryAddresse || ''}, ${addressData.optionalAddress || ''}, ${addressData.postalCode || ''} ${addressData.city || ''}, ${addressData.country || ''}`.trim();
  };

  return (
    <>
      <Stack
        spacing={{ xs: 3, md: 5 }}
        direction={{ xs: 'column', md: 'row' }}
        divider={
          <Divider
            flexItem
            orientation={mdUp ? 'vertical' : 'horizontal'}
            sx={{ borderStyle: 'dashed' }}
          />
        }
        sx={{ p: 3 }}
      >
        <Stack sx={{ width: 1 }}>
          <Typography variant="h6" sx={{ color: 'text.disabled', mb: 1 }}>
            From:
          </Typography>

          {loadingManager ? (
            <CircularProgress size={24} />
          ) : error ? (
            <Typography color="error">{error}</Typography>
          ) : managerInfo ? (
            <Stack spacing={1}>
              <Typography variant="subtitle2">{managerInfo.name}</Typography>
              <Typography variant="body2">{managerInfo.email}</Typography>
              <Typography variant="body2">{managerInfo.phoneNumber}</Typography>
              <Typography variant="body2">{managerInfo.address}</Typography>
            </Stack>
          ) : (
            <Typography color="error">No manager information available</Typography>
          )}
        </Stack>

        <Stack sx={{ width: 1 }}>
          <Stack direction="row" alignItems="center" sx={{ mb: 1 }}>
            <Typography variant="h6" sx={{ color: 'text.disabled', flexGrow: 1 }}>
              To:
            </Typography>

            <IconButton onClick={to.onTrue}>
              <Iconify icon="mingcute:add-line" />
            </IconButton>
          </Stack>

          {invoiceClient ? (
            <Stack spacing={1}>
              <Typography variant="subtitle2">{invoiceClient.company}</Typography>
              <Typography variant="body2">{`${invoiceClient.apartement} ${invoiceClient.street} - ${invoiceClient.city}/${invoiceClient.postalCode}, ${invoiceClient.country}`}</Typography>
              <Typography variant="body2">{invoiceClient.phoneNumber}</Typography>
              <Typography variant="body2">{invoiceClient.emailAddress}</Typography>
            </Stack>
          ) : (
            <Typography typography="caption" sx={{ color: 'error.main' }}>
              {(errors.invoiceClient as any)?.message}
            </Typography>
          )}
        </Stack>
      </Stack>

      <AddressListDialog
        title="Customers"
        open={to.value}
        onClose={to.onFalse}
        selected={invoiceClient || null}
        onSelect={(address) => setValue('invoiceClient', address)}
        list={clients}
        isLoading={isLoading}
        action={
          <Button
            size="small"
            startIcon={<Iconify icon="mingcute:add-line" />}
            onClick={invoiceClientForm.onTrue}
            sx={{ alignSelf: 'flex-end' }}
          >
            New
          </Button>
        }
      />
      <InvoiceClientNewForm
        open={invoiceClientForm.value}
        onClose={invoiceClientForm.onFalse}
        onCreate={handleAddNewInvoiceClient}
      />
    </>
  );
}