'use client';

import React, { useEffect } from 'react';
import {
  Typography,
  Grid,
  Box,
} from '@mui/material';
import { useFormik } from 'formik';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import { ILeave } from '@/shared/types/leave';
import { leaveFormFields } from '../utils/form-fields-conge';
import { congeSchema } from '../utils/conge-schema';
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface CongeFormProps {
  conge: ILeave;
  mode: ModeType;
  onSave: (updatedConge: ILeave) => void;
  onEdit: (updatedConge: ILeave) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, newContent: ILeave) => void;
  tabId: string;
}

export default function CongeForm({
  conge,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: CongeFormProps) {
  const isReadOnly = mode === 'view';

  const formik = useFormik<ILeave>({
    initialValues: conge,
    validationSchema: congeSchema,
    enableReinitialize: true,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
  });

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

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

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <FormContainer titre="Demande de congé">
        <ConditionalComponent isValid={isReadOnly}>
          <EditExportButtons
            onEdit={() => onEdit(formik.values)}
            onExport={() => void 0}
            tooltipTitle="le congé"
          />
        </ConditionalComponent>
        
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={4}>
            {leaveFormFields.map((field: FormFieldType<ILeave>) => (
              <Grid 
                item 
                xs={12} 
                sm={4}
                key={field.name}
              >
                {renderField(field)}
              </Grid>
            ))}

            <Grid item xs={12}>
              <Box display="flex" alignItems="center" gap={4}>
                <Typography sx={{ color: 'primary.main' }}>
                  Pièce justificative
                </Typography>
                <AddButton
                  variant="contained"
                  sx={{ minHeight: '43px' }}
                  endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                  disabled={isReadOnly}
                >
                  Importez un document
                </AddButton>
              </Box>
            </Grid>
            <Grid item xs={12}>
              <ConditionalComponent isValid={!isReadOnly}>
                <ActionButtons 
                  onSave={() => {
                    formik.validateForm().then((errors) => {
                      formik.submitForm()
                    })
                  }} 
                  onCancel={() => onClose(false)} 
                  mode={mode}
                />
              </ConditionalComponent>
            </Grid>
          </Grid>
        </form>
      </FormContainer>
    </LocalizationProvider>
  );
}