import type React from 'react';
import { Grid, Typography, Box } from '@mui/material';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import { useFormikContext } from 'formik';
import FontAwesome from '@/shared/components/fontawesome';
import { centerFlexColumn } from '@/shared/theme/css';
import { TableColumn, TableType, type FormFieldType, type ModeType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import {
  detailsEtabformFields,
  observationformFields,
  responsableEtabformFields,
} from '../utils/form-fields-establishment';
import { AddButton } from '@/shared/components/table/styles';
import FormContainer from '@/layouts/form/form-container';
import FormField from '@/shared/components/form/form-field';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { EstablishmentRequest, EstablishmentManager } from '@/shared/types/establishment';
import { useRef, useState } from 'react';

interface EtablissementTabProps {
  renderField: (field: FormFieldType<EstablishmentRequest>) => React.ReactNode;
  mode: ModeType;
  onClose: () => void;
  onEdit: () => void;
  etablissement: EstablishmentRequest;
  tableHead: TableColumn[];
  zoneOptions: { label: string, value: string }[];
  departmentOptions: { label: string, value: string }[];
}

export default function EstablishmentDetailsForm({
  mode,
  onClose,
  onEdit,
  renderField,
  etablissement,
  tableHead,
  zoneOptions,
  departmentOptions,
}: EtablissementTabProps) {
  const { values, setFieldValue, errors, touched, handleBlur, handleSubmit } = useFormikContext<EstablishmentRequest>();
  const isReadOnly = mode === 'view';
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFileName, setSelectedFileName] = useState<string>('');

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      const file = files[0];
      setSelectedFileName(file.name);
    }
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const renderFieldResponsable = (field: FormFieldType<EstablishmentManager>) => (
    <FormField
      field={field}
      value={values.establishmentManager?.[field.name]}
      onChange={(name, value) => setFieldValue(`establishmentManager.${name}`, value)}
      error={
        touched.establishmentManager?.[field.name] && errors.establishmentManager?.[field.name]
          ? String(errors.establishmentManager[field.name])
          : undefined
      }
      isReadOnly={isReadOnly}
      onBlur={(e) => handleBlur({ target: { name: `establishmentManager.${field.name}` } })}
    />
  );

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={onEdit}
          tooltipTitle={TableType.Etablissement}
          dataRow={etablissement}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <form onSubmit={handleSubmit}>
        <Grid container spacing={5}>
          {detailsEtabformFields(zoneOptions, departmentOptions).map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <Grid
            item
            xs={12}
            sm={4}
            sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}
            key="importezDocument"
          >
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography
                sx={{
                  color: isReadOnly ? "text.disabled" : "primary.main",
                  display: { sm: 'none', md: 'block' },
                }}
              >
                Importer document
              </Typography>
              <AddButton
                variant="contained"
                onClick={handleImportClick}
                sx={{ minHeight: '43px' }}
                endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                disabled={isReadOnly}
              >
                Importez un document
              </AddButton>
            </Box>
            <ConditionalComponent isValid={selectedFileName !== ''}>
              <Typography
                variant="body2"
                sx={{
                  color: 'text.primary',
                  fontStyle: 'italic',
                  fontSize: '0.875rem',
                }}
              >
                Fichier sélectionné : {selectedFileName}
              </Typography>
            </ConditionalComponent>
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileUpload}
              accept=".xlsx,.xls,.csv,.pdf"
              style={{ display: 'none' }}
            />
          </Grid>
          {observationformFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>
        <FormContainer sx={{ mt: 1 }} titre="Responsable de l'établissement" isSousElemnt>
          <Grid container spacing={5} sx={{ pt: 1 }}>
            {responsableEtabformFields.map((field) => (
              <Grid
                item
                xs={12}
                sx={field.name === 'civility' ? centerFlexColumn : undefined}
                sm={4}
                key={field.name as string}
              >
                {renderFieldResponsable(field)}
              </Grid>
            ))}
            <ConditionalComponent isValid={!isReadOnly}>
              <Grid item xs={12}>
                <ActionButtons onSave={handleSubmit} onCancel={onClose} mode={mode} />
              </Grid>
            </ConditionalComponent>
          </Grid>
        </FormContainer>
      </form>
    </>
  );
}
