'use client';

import React, { useEffect, useMemo } from 'react';
import {
  Grid,
} from '@mui/material';
import { _CONTRACT_STATUS } from '../../../_mock/_Contrat';
import {
  centerFlexColumn,
} from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import { IAbsence } from '@/shared/types/absence';
import FormContainer from '@/layouts/form/form-container';
import { useFormFieldsAbsence } from '../utils/form-fields-absence';
import { _OPTION_DEMANDE } from '@/shared/sections/absence/utils/form-fields-absence';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { useFormik } from 'formik';
import { absenceValidationSchema } from '../utils/absence-validation-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useAbsenceStore } from '@/shared/api/stores/absenceStore';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { mapFrontToBackState } from '@/shared/types/absence';
interface AbsenceFormProps {
  absence: IAbsence;
  mode: ModeType;
  onSave: (updatedAbsence: IAbsence) => void;
  onEdit: (updatedAbsence: IAbsence) => void;
  onClose: (isSaved: boolean) => void;
  isTraiteAbsence?:boolean;
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, newContent: IAbsence) => void
  tabId?: string
}

export default function AbsenceForm({
  absence,
  mode,
  onSave,
  onClose,
  onEdit,
  isTraiteAbsence,
  tableHead,
  updateTabContent,
  tabId,
}: AbsenceFormProps) {
  const { updateAbsence, createAbsence } = useAbsenceStore();
  const { passengers, searchPassengers } = usePassengerStore();
  
  useEffect(() => {
 
    searchPassengers();
  }, []);

  const isReadOnly = mode === 'view';
  const isCreating = mode === 'add';
  
  const handlePassengerSelect = (selectedValue: string | number) => {
    console.log('Selected value:', selectedValue);
    if (!selectedValue) return;
    
    const selectedPassenger = usePassengerStore.getState().passengers.find(p => p.id.toString() === selectedValue.toString());
    console.log('Found passenger:', selectedPassenger);
    
    if (selectedPassenger) {
      const usagerObject = {
        id: selectedPassenger.id,
        firstName: selectedPassenger.firstName,
        lastName: selectedPassenger.lastName,
        establishmentName: selectedPassenger.establishmentName,
        departmentName: selectedPassenger.departmentName
      };
      console.log('Setting usager to:', usagerObject);
      
      formik.setFieldValue('usager', usagerObject);
      formik.setFieldValue('etablissement', selectedPassenger.establishmentName);
      formik.setFieldValue('departement', selectedPassenger.departmentName);
    }
  };

  const formik = useFormik<IAbsence>({
    initialValues: {
      ...absence,
      usager: absence.usager || {
        id: '',
        establishmentName: '',
        departmentName: '',
        firstName: '',
        lastName: ''
      },
      etat: Array.isArray(absence.etat) ? absence.etat[0] : (absence.etat || 'Non traité'),
      sensAR: Array.isArray(absence.sensAR) ? absence.sensAR : [absence.sensAR],
    },
    enableReinitialize: true,
    validationSchema: absenceValidationSchema,
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: async (values) => {
      try {
        const formattedData = {
          passengerId: typeof values.usager === 'object' ? values.usager.id : values.usager,
          state: Array.isArray(values.etat) 
            ? values.etat.map(state => mapFrontToBackState(state))
            : mapFrontToBackState(values.etat),
          startDate: values.dateDebut,
          endDate: values.dateFin,
          forecastDate: values.previentLe,
          concernedTrip: values.sensAR.map(v => v === 'aller' ? 'Outbound' : 'Return'),
          observations: values.observation || '',
          receivingMethod: values.modeReception,
          comment: values.comment || '',
          reportedBy: values.par,
        };

        if (mode === 'add') {
          await createAbsence(formattedData);
        } else {
          await updateAbsence(parseInt(values.id), formattedData);
        }
        
        onSave(values);
        onClose(true);
      } catch (error) {
        console.error('Failed to save absence:', error);
      }
    },
  }); 

  useEffect(() => {

    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<IAbsence>) => {
    const fieldName = field.name as keyof IAbsence;
    const error = formik.errors[fieldName];
    const touched = formik.touched[fieldName];
    
    if (field.name === 'usager') {
    }
    
    const displayValue = field.name === 'usager' ? 
      (typeof formik.values.usager === 'object' ? 
        formik.values.usager.id.toString()
        : formik.values.usager) 
      : formik.values[field.name];


    return (
      <FormField
        field={field}
        value={displayValue}
        onChange={(name, value) => {
          console.log('onChange triggered:', { name, value });
          if (field.name === 'usager') {
            handlePassengerSelect(value);
          } else {
            formik.setFieldValue(name, value);
            formik.setFieldTouched(name, true, false);
          }
        }}
        error={touched && error ? String(error) : undefined}
        isReadOnly={isReadOnly}
        onBlur={formik.handleBlur}
      />
    );
  };



  return (
    <FormContainer titre="Fiche Absence" >
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={isTraiteAbsence ? undefined : () => onEdit(absence)}
          tooltipTitle={TableType.AbsenceUsager}
          dataRow={absence}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <form onSubmit={formik.handleSubmit} noValidate>
        <Grid container spacing={4}>
          {useFormFieldsAbsence(_OPTION_DEMANDE).map((field) => (
            <Grid item xs={12} sx={field.name === 'sensAR' ? centerFlexColumn : undefined} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}

          <Grid item xs={12}>
            <ConditionalComponent isValid={!isReadOnly}>
              <ActionButtons 
                onSave={formik.handleSubmit}
                onCancel={() => onClose(false)} 
                mode={mode} 
              />
            </ConditionalComponent>
          </Grid>
        </Grid>
      </form>
    </FormContainer>
  );
}
