'use client';

import { Grid } from '@mui/material';
import { useEffect, useState } from 'react';
import { IAvenant, ICircuit } from '@/shared/types/circuit';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import FormContainer from '@/layouts/form/form-container';
import { mainAvenantformFields } from '../utils/form-fields-avenant';
import CircuittrajetsForm from '../../circuit/components/circuit-form/trajet/trajets-list';
import AvenantDetailsForm from '../components/avenant-details';
import AvenantHoraireForm from '../components/avenant-horaire';
import { useAmendmentStore } from '@/shared/api/stores/amendmentStore';
import { AmendmentDetailDTO } from '@/shared/types/amendment';
import { exportComprehensiveAvenant } from '@/shared/services/amendment-export.service';
import { Stack, IconButton } from '@mui/material';
import { faFileExport } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { iconButtonStyles } from '@/shared/theme/css';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

// Empty circuit data
const EMPTY_CIRCUIT: ICircuit = {
  id: '',
  etat: 'non_controle',
  adresseEtablissement: {
    address: '',
    lat: 0,
    lng: 0,
    city: '',
    postalCode: '',
    country: '',
    formattedAddress: ''
  },
  etablissement: '',
  dateDebut: '',
  dateFin: '',
  chauffeur: '',
  grillePrix: '',
  colorCode: '#FFFFFF',
  observation: '',
  typeCalcul: 'calculAutomatique',
  codeCircuit: '',
  intitule: '',
  clientDO: '',
  departement: '',
  dateDernierAvenant: '',
  numeroContrat: '',
  isActive: true,
  numeroLot: '',
  type: '',
};

// Map API model to internal model
const mapAmendmentToAvenant = (amendmentResponse: AmendmentDetailDTO): IAvenant => {
  const amendment = amendmentResponse.amendment;

  // Map API calculationType values to frontend values
  const mapCalculationType = (apiCalculationType: string | undefined): string => {
    switch (apiCalculationType) {
      case 'FIXED':
        return 'calculAutomatique';
      case 'MANUAL':
        return 'calculManuel';
      case 'AUTO':
        return 'calculAutomatique';
      default:
        return 'calculAutomatique'; // Default fallback
    }
  };

  return {
    id: amendment.id,
    dateApplication: amendment.applicationDate,
    etat: amendment.status === 'controle' ? 'controle' : 'non_controle',
    codeCircuit: amendment.circuitCode || '',
    codeAvenant: amendment.amendmentCode,
    intitule: amendment.title,
    objetAvenant: amendment.amendmentPurpose || '',
    type: amendment.type || '',
    dateFin: amendment.endDate || '',
    etablissement: amendment.establishment || '',
    chauffeur: amendment.driver,
    departement: amendment.company,
    clientDO: amendment.clientDO,
    isActive: amendment.active,
    objet: amendment.purpose || '',
    typeCalcul: mapCalculationType(amendment.calculationType),
  };
};

interface CircuitFormProps {
  avenant: IAvenant;
  isMainTable?: boolean;
  mode: ModeType;
  onSave?: (updatedContract: IAvenant) => void;
  onEdit?: (updatedContract: IAvenant) => void;
  onClose: (isSaved: boolean) => void;
  hasBorder?:boolean;
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, newContent: IAvenant) => void
  tabId?: string
}

export default function AvenantForm({ avenant, mode, onSave, onClose, onEdit, isMainTable, hasBorder, tableHead, updateTabContent, tabId }: CircuitFormProps) {
  const [formData, setFormData] = useState<IAvenant>(avenant);
  const [circuit, setCircuit] = useState<ICircuit>(EMPTY_CIRCUIT);
  const { getAmendmentById, amendment, loading, error } = useAmendmentStore();

  // Fetch amendment details when component mounts or avenant ID changes
  useEffect(() => {
    if (avenant.id && mode === 'view') {
      getAmendmentById(avenant.id);
    }
  }, [avenant.id, mode, getAmendmentById]);

  // Update form data when amendment details are fetched
  useEffect(() => {
    if (amendment) {
      const mappedAvenant = mapAmendmentToAvenant(amendment);
      setFormData(mappedAvenant);
    } else {
      setFormData(avenant);
    }
  }, [amendment, avenant]);

  useEffect(() => {
    // Map amendment data to circuit structure for the details form
    if (amendment) {
      const amendmentData = amendment.amendment;

      // Map API calculationType values to frontend values
      const mapCalculationType = (apiCalculationType: string | undefined): string => {
        switch (apiCalculationType) {
          case 'FIXED':
            return 'calculAutomatique';
          case 'MANUAL':
            return 'calculManuel';
          case 'AUTO':
            return 'calculAutomatique';
          default:
            return 'calculAutomatique'; // Default fallback
        }
      };

      const mappedCircuit = {
        ...EMPTY_CIRCUIT,
        id: amendmentData.id,
        etat: amendmentData.status,
        etablissement: amendmentData.establishment || '',
        chauffeur: amendmentData.driver || '',
        dateDebut: amendmentData.applicationDate || '',
        dateFin: amendmentData.endDate || '',
        typeCalcul: mapCalculationType(amendmentData.calculationType),
        grillePrix: amendmentData.pricingGrid || '',
        colorCode: amendmentData.categorizationColor || '#FFFFFF',
        observation: amendmentData.observation || '',
        // Map address if available
        adresseEtablissement: {
          address: amendmentData.coverage || '',
          lat: 0,
          lng: 0,
          city: '',
          postalCode: '',
          country: '',
          formattedAddress: amendmentData.coverage || ''
        },
        // Map other fields from amendment data
        intitule: amendmentData.title || '',
        clientDO: amendmentData.clientDO || '',
        departement: amendmentData.company || '',
        isActive: amendmentData.active,
        codeCircuit: amendmentData.circuitCode || '',
      };
      setCircuit(mappedCircuit);
    } else {
      // Fallback to basic mapping from formData
      setCircuit({
        ...EMPTY_CIRCUIT,
        id: formData.id,
        etablissement: formData.etablissement,
        chauffeur: formData.chauffeur,
        etat: formData.etat,
        dateDebut: formData.dateApplication,
        dateFin: formData.dateFin,
        intitule: formData.intitule,
        clientDO: formData.clientDO,
        departement: formData.departement,
        isActive: formData.isActive,
        codeCircuit: formData.codeCircuit,
        typeCalcul: formData.typeCalcul || 'calculAutomatique',
      });
    }
  }, [amendment, formData]);

  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';

  const handleEdit = () => {
    if (onEdit) {
      onEdit(formData);
    }
    onClose(true);
  };

  const handleSave = () => {
    if (onSave) {
      onSave(formData);
    }
    onClose(true);
  };

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formData)
    }
  }, [formData, updateTabContent, tabId, mode])

  const handleComprehensiveExport = async () => {
    if (formData.id) {
      try {
        await exportComprehensiveAvenant(formData.id);
      } catch (error) {
        console.error('Failed to export comprehensive avenant:', error);
      }
    }
  };

  const renderField = (field: FormFieldType<IAvenant>) => (
    <FormField
      field={field}
      value={formData[field.name]}
      onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
      isReadOnly={true}
    />
  );

  const tabs = [
    {
      label: isMainTable ? 'Details avenant' : 'Circuit',
      content: <AvenantDetailsForm
        tableHead={tableHead}
        isReadOnly={isReadOnly}
        isEditMode={isEditMode}
        circuit={circuit}
        {...(onEdit && { onEdit: handleEdit })}
        onClose={(isSaved) => onClose(isSaved)}
        handleSave={handleSave}
      />
    },
    {
      label: 'Trajets',
      content: <CircuittrajetsForm schedules={amendment?.schedules?.content} trips={amendment?.trips} />
    },
    { label: 'Horaires',  content: (
      <AvenantHoraireForm
        onEdit={handleEdit}
        onClose={(isSaved) => onClose(isSaved)}
        onSave={handleSave}
        mode={mode}
        avenant={formData}
        schedules={amendment?.schedules}
      />
    )},
   ];

  return (
    <FormContainer titre="Fiche d'un avenant" isSousElemnt={!isMainTable} hasBorder={hasBorder}>
      <form>
        <ConditionalComponent isValid={isReadOnly && !!formData.id}>
          <Stack direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
            <CustomTooltip title="Exporter avenant complet (CSV)" arrow>
              <IconButton onClick={handleComprehensiveExport} sx={iconButtonStyles}>
                <FontAwesome icon={faFileExport} width={16} />
              </IconButton>
            </CustomTooltip>
          </Stack>
        </ConditionalComponent>
        <Grid container spacing={6} >
          {mainAvenantformFields.map((avenantField) => (
            <Grid
              item
              xs={12}
              sm={avenantField.name === 'codeAvenant' ? 4 : 8}
              key={avenantField.name}
            >
              {renderField(avenantField)}
            </Grid>
          ))}
        </Grid>
        <TabbedForm tabs={tabs} sx={{mt:4}}  />
      </form>
    </FormContainer>
  );
}
