import React, { useState, useEffect } from 'react';
import { FieldErrors, useFormContext } from 'react-hook-form';
import Stack from '@mui/material/Stack';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
import { useResponsive } from '@/hooks/use-responsive';
import { getUserByEmail, getUserById } from '@/shared/api/user';
import { getGroupWithAddress } from '@/shared/api/invoice';
import { IInvoiceClient } from '@/shared/types/invoice';

export default function InvoiceNewEditAddress() {
  const { watch, formState: { errors } } = useFormContext();
  const mdUp = useResponsive('up', 'md');
  const { invoiceClient, responsibleId } = watch();

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

  useEffect(() => {
    const fetchManagerInfo = async () => {
      if (responsibleId === undefined) {
        setLoadingManager(false);
        return;
      }
  
      setLoadingManager(true);
      setError(null);
      try {
        const userData = await getUserById(responsibleId);
        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)
          };
        } else {
          managerInfoData = {
            name: `${userData.firstName} ${userData.lastName}`,
            email: userData.email,
            phoneNumber: userData.phoneNumber,
            address: formatAddress(userData.address)
          };
          
        }
  
        setManagerInfo(managerInfoData);
  
      } catch (error) {
        console.error('Error fetching manager info:', error);
        setError('Failed to load manager information');
      } finally {
        setLoadingManager(false);
      }
    };
  
    fetchManagerInfo();
  }, [responsibleId]);

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

  const renderManagerInfo = () => {
    if (loadingManager) {
      return <CircularProgress size={24} />;
    }
    if (error) {
      return <Typography color="error">{error}</Typography>;
    }
    if (managerInfo) {
      return (
        <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>
      );
    }
    return <Typography color="error">No manager information available</Typography>;
  };

  const renderInvoiceClient = () => {
    if (invoiceClient) {
      return (
        <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>
      );
    }
    return (
      <Typography typography="caption" sx={{ color: 'error.main' }}>
        {(errors.invoiceClient as FieldErrors<IInvoiceClient>)?.root?.message || 'Invalid client information'}
      </Typography>
    );
  };

  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>
        {renderManagerInfo()}
      </Stack>

      <Stack sx={{ width: 1 }}>
        <Typography variant="h6" sx={{ color: 'text.disabled', mb: 1 }}>
          To:
        </Typography>
        {renderInvoiceClient()}
      </Stack>
    </Stack>
  );
}