'use client';

import React from 'react';
import { Dialog, DialogTitle, DialogContent, Box } from '@mui/material';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserTie } from '@fortawesome/free-solid-svg-icons';
import type { AddressData, TableColumn } from '@/shared/types/common';
import { AddressDTO, AddressType, type IClient } from '@/shared/types/client';
import ClientForm from '@/shared/sections/client/view/client-new-view';
import { enqueueSnackbar } from 'notistack';
import { useClientStore } from '@/shared/api/stores/userStore';
import { INITIAL_CLIENT_DATA } from '@/shared/_mock/_client';

interface CreateClientModalProps {
  open: boolean;
  onClose: (forceClose?: boolean) => void;
  tableHead?: TableColumn[];
  PaperProps?: object;
}

const CreateClientModal: React.FC<CreateClientModalProps> = ({
  open,
  onClose,
  tableHead = [],
  PaperProps,
}) => {
  const { error, addClient} = useClientStore();
  const handleClient = async (client: IClient) => {
    try {
      await handleSave(client);
    } catch (error) {
      console.error('Erreur lors du traitement du client :', error);
    }
  };
  const getFormatedAddress = (mapAdresse: AddressData, adresseId: string): AddressDTO => {
    const street = mapAdresse.address.split(',')[0].trim();
    const city = mapAdresse.city || '';
    const postalCode = mapAdresse.postalCode || '';
    const country = mapAdresse.country || '';
    const additionalAddress = mapAdresse.formattedAddress || '';

    return {
      id: adresseId,
      createdAt: '',
      updatedAt: '',
      street, // Rue extraite
      city, // Ville provenant de mapAdresse
      country, // Pays provenant de mapAdresse
      zipCode: postalCode, // Code postal provenant de mapAdresse
      latitude: mapAdresse.lat as number, // Latitude
      longitude: mapAdresse.lng as number, // Longitude
      addressType: AddressType.CLIENT,
      additionalAddress: additionalAddress || undefined, // Adresse complémentaire
    };
  };

  const handleSave = async (client: IClient) => {
    try {
      const processedClient: IClient = {
        ...client,
        id: '0',
        typeClient: client.typeClient,
        roles: [
          {
            id: '0',
            name: 'CLIENT_DO',
            description: '',
          },
        ],
        agency_id: Number(client.agencyName),
        agencyName: client.agencyName,
        departmentId: Number(client.department),
        department: client.department,
        addresses: client.mapAdresse?.address ? [getFormatedAddress(client.mapAdresse, '0')] : [],
      };
      await addClient(processedClient);
      if (error == null) {
        enqueueSnackbar('Client ajouté avec succès!', { variant: 'success' });
      } else {
        enqueueSnackbar('Client ajouté avec succès!');
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de l'ajout du client.", { variant: 'error' });
      console.error('Erreur lors de la sauvegarde du client : ', error);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={() => onClose(false)}
      fullWidth
      maxWidth="md"
      scroll="body"
      PaperProps={{
        sx: {
          width: '80%',
          maxHeight: '90vh',
          maxWidth: 'none',
          borderRadius: '12px',
        },
        ...PaperProps,
      }}
    >
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <FontAwesomeIcon icon={faUserTie} />
          Créer un nouveau client
        </Box>
      </DialogTitle>

      <DialogContent
        dividers={false}
        sx={{
          maxHeight: 'calc(90vh - 64px)',
          overflowY: 'auto',
          paddingRight: 0,
        }}
      >
        <ClientForm
          client={INITIAL_CLIENT_DATA}
          mode="add"
          onSave={handleClient}
          onEdit={() => { }}
          onClose={onClose}
          tableHead={tableHead}
          updateTabContent={() => { }}
          tabId="create-client-modal"
        />
      </DialogContent>
    </Dialog>
  );
};

export default CreateClientModal;