'use client';

import { useState, useEffect } from 'react';
import { Grid, Typography } from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import { TypeImport, type FormFieldType, type ModeType } from '@/shared/types/common';
import type { IFileImport } from '@/shared/types/vacance';
import FormContainer from '@/layouts/form/form-container';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { fileImportFormFields } from '../utils/form-fields-vacance';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import ZoneDetails from '../components/zone-details';
import { DEFAULT_ZONES } from '@/shared/_mock/_vacance';
import ActionButtons from '@/shared/components/form/buttons-action';
import { tabsBorder } from '@/shared/theme/css';
import { useBoolean } from '@/hooks';
import MassUploadFile from '@/shared/components/mass-import/mass-upload-file';

interface VacationFormProps {
  vacation: IFileImport;
  mode: ModeType;
  onSave: (updatedVacation: IFileImport) => void;
  onEdit: (updatedVacation: IFileImport) => void;
  onClose: () => void;
  isChild?: boolean;
}

export default function VacationForm({
  vacation,
  mode,
  onSave,
  onClose,
  onEdit,
  isChild = false,
}: VacationFormProps) {
  const uploadFile = useBoolean(false);
  const [formData, setFormData] = useState<IFileImport>(() => ({
    ...vacation,
    zones: vacation.zones || DEFAULT_ZONES,
  }));
  const [currentStep, setCurrentStep] = useState<"import" | "details">(() => {
    return "import"
  })
  useEffect(() => {
    setCurrentStep("import")
  }, [vacation.id])

  useEffect(() => {
    setFormData({
      ...vacation,
      zones: vacation.zones || DEFAULT_ZONES,
    });
  }, [vacation]);

  const handleSave = () => {
    onSave(formData);
    onClose();
  };

  const handleContinue = () => {
    setCurrentStep('details');
  };

  const isReadOnly = mode === 'view';

  const renderField = (field: FormFieldType<IFileImport>) => (
    <FormField
      key={`${field.name}-${vacation.id}`}
      field={field}
      value={formData[field.name]}
      onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
      isReadOnly={isReadOnly}
    />
  );

  return (
    <FormContainer sx={isChild ? { ...tabsBorder } : undefined} titre="Fiche Période">
      {isReadOnly ? (
        <EditExportButtons
          onEdit={() => onEdit(vacation)}
          onExport={() => void 0}
          tooltipTitle="période des vacances"
        />
      ) : null}
      <form>
        {currentStep === 'import' ? (
          <Grid container spacing={4}>
            {fileImportFormFields.map((field) => (
              <Grid item xs={12} sm={4} key={`${field.name}-${vacation.id}`}>
                {renderField(field)}
              </Grid>
            ))}
            <Grid item xs={12} sm={6} xl={4} key={`import-${vacation.id}`} sx={{ display: 'flex' }}>
              <Typography sx={{ color: isReadOnly ? 'text.disabled' : 'primary.main', m: 'auto' }}>
                Importer une période
              </Typography>
              <AddButton
                variant="contained"
                onClick={uploadFile.onTrue}
                sx={{ minHeight: '43px' }}
                endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                disabled={isReadOnly}
              >
                Importez une période
              </AddButton>
            </Grid>
          </Grid>
        ) : (
          <ZoneDetails formData={formData} setFormData={setFormData} isReadOnly={isReadOnly} />
        )}

        <Grid item xs={12}>
          {!isReadOnly ? (
            <ActionButtons
              onSave={currentStep === 'import' ? handleContinue : () => setCurrentStep('import')}
              onCancel={onClose}
              mode={mode}
              onValidate={currentStep === 'import' ? undefined : handleSave}
              thirdButtonText="Enregistrer"
              secoundButtonText={currentStep === 'import' ? 'Continuer' : 'Retourner'}
            />
          ) : (
            <></>
          )}
        </Grid>
      </form>
      {uploadFile.value ? 
              <MassUploadFile
                open={uploadFile.value} 
                onClose={uploadFile.onFalse}
                type={TypeImport.VACANCE}
                withData={mode !== 'add'}
              /> : <></>}
    </FormContainer>
  );
}
