'use client';

import React, { useState, useEffect } from 'react';
import { Typography, Grid, Chip } from '@mui/material';
import dayjs from 'dayjs';
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 { ITrajet, EtatTrajet, TypeTrajet, BinaryQuestion } from '@/shared/types/trajet';
import { Sens } from '@/shared/types/circuit';
import { trajetformFields } from '../utils/form-fields-trajet';
import JoursAttribuesInput from '@/shared/components/form/jours-attribues-input';
import FormContainer from '@/layouts/form/form-container';
import DetailsTrajet from '../components/details-trajet';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import AddPointModal from '../components/add-point-modal';
import ConditionalComponent from '../../../components/table/ConditionalComponent';

interface TrajetFormProps {
  trajet: ITrajet;
  mode: ModeType;
  onSave?: (updatedTrajet: ITrajet) => void;
  onEdit?: (updatedTrajet: ITrajet) => void;
  onClose: () => void;
  isDrawerElement?: boolean
  hasBorder?: boolean;
  tableHead: TableColumn[];
}

export default function TrajetForm({ trajet, mode, onSave, onClose, onEdit, isDrawerElement, hasBorder, tableHead }: TrajetFormProps) {
  const [formData, setFormData] = useState<ITrajet>(trajet);
  const [modalOpen, setModalOpen] = useState(false);

  const handleOpenModal = () => {
    setModalOpen(true);
  };

  const handleCloseModal = () => {
    setModalOpen(false);
  };

  useEffect(() => {
    let etatValue = trajet.etat;
    if (trajet.tripState === "CONTROLE" && !etatValue) {
      etatValue = EtatTrajet.Controle;
    } else if (trajet.tripState === "MODIFIE" && !etatValue) {
      etatValue = EtatTrajet.Modifier;
    } else if (trajet.tripState === "NON_CONTROLE" && !etatValue) {
      etatValue = EtatTrajet.NonControle;
    }

    // Handle rotation value
    let rotationValue = BinaryQuestion.Non;
    const rotationStr = String(trajet.rotation).toLowerCase();
    if (rotationStr === 'oui' || rotationStr === 'true') {
      rotationValue = BinaryQuestion.Oui;
    }

    // Handle peages value
    let peagesValue = BinaryQuestion.Non;
    const hasTolls = typeof trajet.hasTolls === 'boolean' 
      ? trajet.hasTolls 
      : trajet.hasTolls === 'oui' || trajet.hasTolls === 'true' || trajet.peages === BinaryQuestion.Oui;
    
    if (hasTolls) {
      peagesValue = BinaryQuestion.Oui;
    }

    const completeData: ITrajet = {
      ...trajet,
      id: trajet.id,
      intitule: trajet.intitule || trajet.days || trajet.id || "",
      circuitAvenant: trajet.circuitAvenant || trajet.circuitId || "",
      dateDebut: trajet.dateDebut || trajet.dateTrip || trajet.avenantDate || "",
      etat: etatValue || trajet.etatControle || EtatTrajet.NonControle,
      typeTrajet: trajet.typeTrajet || (trajet.tripType === "NORMAL" ? TypeTrajet.Normal : TypeTrajet.personnalise),
      chauffeur: trajet.chauffeur || "",
      vehicule: trajet.vehicule || trajet.vehicleName || "",
      sensAR: trajet.sensAR || (trajet.sens === "DEPARTURE" ? Sens.Aller : Sens.Retour) || trajet.statut || Sens.Aller,
      rotation: rotationValue,
      peages: peagesValue,
      nombreUsagers: trajet.nombreUsagers || trajet.nbrUsagers || 0,
      nombreEtablissements: trajet.nombreEtablissements || trajet.nbrEtablissements || 0,
      origine: trajet.origine || trajet.origin || "",
      destination: trajet.destination || "",
      distanceKm: trajet.distanceKm || 0,
      duree: trajet.duree || trajet.duration || "",
      observationPersonnalisation: trajet.observationPersonnalisation || trajet.customizationNote || "",
      observationFeuilleRoute: trajet.observationFeuilleRoute || trajet.routeSheetNote || "",
      datePersonnalisation: trajet.datePersonnalisation || trajet.customizedDate || "",
      societe: trajet.societe || "",
      client: trajet.client || "",
      days: trajet.days|| "",
    };
    setFormData(completeData);
  }, [trajet]);



  const handleSave = () => {
    if (onSave) {
      // Ensure peages is properly set before saving
      const dataToSave = {
        ...formData,
        hasTolls: formData.peages === BinaryQuestion.Oui,
      };
      onSave(dataToSave);
    }
    onClose();
  };

  const isReadOnly = mode === 'view';
  const isFieldDisabledInCopyMode = (fieldName: string) => {
    if (mode !== "copy") return false
    if (fieldName === "observationPersonnalisation") return false
    return !formData.observationPersonnalisation
  }
  
  const renderField = (field: FormFieldType<ITrajet>) => {
    let fieldValue = formData[field.name as keyof ITrajet];

    // Special handling for vehicle field
    if (field.name === 'vehicule' && !fieldValue && formData.vehicleName) {
      fieldValue = formData.vehicleName;
    }

    // Special handling for typeTrajet field
    if (field.name === 'typeTrajet') {

      if (!fieldValue || (fieldValue !== TypeTrajet.Normal && fieldValue !== TypeTrajet.personnalise)) {
        fieldValue = formData.tripType === "NORMAL" ? TypeTrajet.Normal : TypeTrajet.personnalise;
      }
    }

    // Vérifier si la valeur est undefined ou null et fournir une valeur par défaut
    if (fieldValue === undefined || fieldValue === null) {
      switch (field.type) {
        case 'text':
          fieldValue = '';
          break;
        case 'number':
          fieldValue = 0;
          break;
        case 'select':
          fieldValue = '';
          break;
        case 'date':
          fieldValue = '';
          break;
        default:
          fieldValue = '';
      }
    }
   
    const isFieldDisabled = isReadOnly || isFieldDisabledInCopyMode(field.name)

    return (
      <FormField
        field={field}
        value={fieldValue}
        onChange={(name, value) => {

          setFormData((prev) => ({ ...prev, [name]: value }));
        }}
        isReadOnly={isFieldDisabled}
        isDrawerElement={isDrawerElement}
      />
    );
  };


  return (
    <>
      <FormContainer titre="Fiche Trajet" isSousElemnt={isDrawerElement || hasBorder} hasBorder={hasBorder}>
      <ConditionalComponent isValid={!!(formData.typeTrajet === TypeTrajet.personnalise && isDrawerElement)}>
      <Chip label={"Personnalise"} color="error" size="small"
      sx={{
        position: "absolute",
        top: 27,
        left: 170,
        width: "fit-content",
      }}
      />
      </ConditionalComponent>

        {isReadOnly && onEdit ? (
          <EditExportButtons
            onEdit={() => onEdit(trajet)}
            onExport={() => void 0}
            tooltipTitle={TableType.Trajet}
            dataRow={trajet}
            tableHead={tableHead}
          />
        ) : (
          <></>
        )}
        <form>
          <Grid container spacing={isDrawerElement ? 2 : 4}>
            {trajetformFields.map((field) =>
              field.name === 'jours' ? (
                <React.Fragment key={field.name}>
                  <Grid item sm={12} md={7} xl={isDrawerElement ? 12 : 5} >
                    <Typography sx={{ color: (theme) => theme.palette.primary.main }}>
                      {field.label}
                    </Typography>
                    <JoursAttribuesInput
                      initialJours={trajet.jours}
                      otherJours={[]}
                      onChange={(val) => {
                      }}
                      isReadOnly={mode === "view"}
                    />
                  </Grid>
                  <ConditionalComponent
                    isValid={!isDrawerElement}
                  >
                    <Grid item sm={12} md={1} xl={3} />
                  </ConditionalComponent>
                </React.Fragment>
              ) : (
                <Grid
                  sx={centerFlexColumn}
                  item
                  xs={12}
                  sm={field.type === "textarea" && isDrawerElement ? 6 : 4}
                  key={field.name}
                >
                  {renderField(field)}
                </Grid>
              )
            )}
            <Grid item xs={12}>
              <DetailsTrajet
                mode={mode}
                isDrawerElement={isDrawerElement}
                onAddPoint={handleOpenModal}
                trajetId={formData.id}
              />
            </Grid>

            {/* Action buttons */}
            {mode !== 'view' ? (
              <Grid item xs={12}>
                <ActionButtons onSave={handleSave} onCancel={onClose} mode={mode} />
              </Grid>
            ) : <></>}
          </Grid>
        </form>
      </FormContainer>

      {modalOpen && (
        <AddPointModal
          open={modalOpen}
          onClose={handleCloseModal}
          trajetId={formData.id || ''}
        />
      )}
    </>
  );
}
