'use client';

import React, { useEffect } from 'react';
import { useFormik } from 'formik';
import { Box, Grid, Typography } from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import { type FormFieldType, type ModeType, type TableColumn } from '@/shared/types/common';
import { type IRevision } from '@/shared/types/flottes/revision';
import { revisionFormFields } from '../utils/form-fields-revision';
import FormContainer from '@/layouts/form/form-container';
import { revisionSchema } from '../utils/revision-schema';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import DocumentForm from '@/shared/components/documents/documents-form';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { revisons } from '@/shared/_mock/flottes/_revision';

interface RevisionFormProps {
  revision: IRevision;
  mode: ModeType;
  onSave: (updatedRevision: IRevision) => void;
  onEdit: (updatedRevision: IRevision) => void;
  onClose: () => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges?: (value: boolean) => void;
  updateTabContent?: (tabId: string, newContent: IRevision) => void;
  tabId?: string;
}

export default function RevisionForm({
  revision,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: RevisionFormProps) {
  const isReadOnly = mode === 'view';
  const isAddMode = mode === 'add';
  const revisonsOptions = revisons.map((intervention) => ({ value: intervention.nomIntervention, label: intervention.nomIntervention }))

  const formik = useFormik<IRevision>({
    initialValues: {
      ...revision,
      dateRevision: revision.dateRevision || '',
      dateCT: revision.dateCT || '',
      derniereMiseAJour: new Date().toISOString().split('T')[0],
    },
    validationSchema: revisionSchema,
    onSubmit: (values) => {
      onSave(values);
      if (setHasUnsavedChanges) setHasUnsavedChanges(false);
      onClose();
    },
  });

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

  useEffect(() => {
    if (setHasUnsavedChanges) {
      setHasUnsavedChanges(formik.dirty);
    }
  }, [formik.dirty, setHasUnsavedChanges]);

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

  const RevisionDetails = () => (
    <Box>
      <Typography variant="h6" sx={{ mb: 3, color: 'primary.main', fontWeight: 600 }}>
         Détails révision et entretien 
      </Typography>
      
      <Box sx={{ mb: 4 }}>
        <ConditionalComponent
          isValid={isReadOnly}
          defaultComponent={
            <ActionButtons
              onCancel={onClose}
              onSave={formik.handleSubmit}
              loading={formik.isSubmitting}
            />
          }
        >
          <EditExportButtons
            onEdit={() => onEdit(formik.values)}
          />
        </ConditionalComponent>
      </Box>
      
      <Grid container spacing={3}>
        {revisionFormFields(revisonsOptions).map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </Grid>
    </Box>
  );

  const tabs = [
    {
      label: ' Détails révision et entretien ',
      content: <RevisionDetails />,
    },
  
  ];

  return (
    <FormContainer>
      <TabbedForm tabs={tabs} />
    </FormContainer>
  );
} 