'use client';

import React, { useEffect } from 'react';
import { useFormik } from 'formik';
import {
  Grid,
  IconButton,
  Stack,
  Divider,
} from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import FormContainer from '@/layouts/form/form-container';
import { IVehicleAffectation } from '@/shared/types/flottes/vehicle-affectation';
import { personnelFields, vehiculeFields, carteFields } from '../utils/form-fields-affectation';
import { affectationSchema } from '../utils/affectation-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import { iconButtonStyles } from '@/shared/theme/css';
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { faPenToSquare } from '@fortawesome/free-solid-svg-icons';
import CircuitDriverAssignmentList from '../components/circuit-table-list';
import AssignmentHistoryListView from '../components/history-assignment/assignment-history-list-view';

interface VehicleFormProps {
  affectation: IVehicleAffectation;
  mode: ModeType;
  onSave: (updatedVehicle: IVehicleAffectation) => void;
  onEdit: (updatedVehicle: IVehicleAffectation) => void;
  onClose: () => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: IVehicleAffectation) => void
  tabId?: string
}

export default function AffectationForm({
  affectation,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: VehicleFormProps) {
  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';

  const formik = useFormik<IVehicleAffectation>({
    initialValues: affectation,
    validationSchema: affectationSchema,
    onSubmit: (values) => {
      onSave(values);
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose();
    },
  });

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

  const renderField = (field: FormFieldType<IVehicleAffectation>) => {
    return (
      <FormField
        field={field}
        value={formik.values[field.name as keyof IVehicleAffectation]}
        onChange={(name, value) => formik.setFieldValue(name, value)}
        error={
          formik.touched[field.name as keyof IVehicleAffectation]
            ? (formik.errors[field.name as keyof IVehicleAffectation] as string | undefined)
            : undefined
        }
        onBlur={formik.handleBlur}
        isReadOnly={field.name === 'adressePersonnel' ? true : isReadOnly}
      />
    );
  };

  const tabs = [
    {
      label: 'Attribution Véhicule',
      content: (
        <AssignmentHistoryListView mainMode={mode}/>
      ),
    },
    {
      label: 'Attribution Carte Carburant',
      content: (
        <Grid container spacing={3}>
          {carteFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>
      ),
    },
  ];

  return (
    <FormContainer titre="Fiche d'affectation du véhicule">
      <form onSubmit={formik.handleSubmit}>
      <ConditionalComponent isValid={isReadOnly}>
        <Stack flexGrow={0} direction="row" justifyContent="flex-end" sx={{ mb: 2 }}>
          <CustomTooltip title="edit Affectation" arrow>
            <IconButton onClick={() => onEdit(formik.values)} size="small" sx={iconButtonStyles}>
              <FontAwesome icon={faPenToSquare} width={16} />
            </IconButton>
          </CustomTooltip>
        </Stack>
      </ConditionalComponent>
        <Grid container spacing={3}>
          {personnelFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <Grid item xs={12}>
            <TabbedForm tabs={tabs} />
          </Grid>
          <Grid item xs={12}>
            <ActionButtons onSave={() => formik.submitForm()} onCancel={onClose} mode={mode} />
          </Grid>
        </Grid>
      </form>
      
      <ConditionalComponent isValid={formik.values.personnelType === 'chauffeur'}>
        <Divider sx={{ my: 2, borderColor: 'primary.light' }} />
        <CircuitDriverAssignmentList />
      </ConditionalComponent>
      
    </FormContainer>
  );
}
