import type React from 'react';
import { Grid, Typography, Box, FormHelperText } 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, useEffect, useCallback } from 'react';
import { useUserStore } from '@/shared/api/stores/user-service/user-store';
import CreateInfrastructureModal from '@/shared/components/dialog/create-infrastructure-modal';
import { RenderFieldOptions } from '../view/establishment-form-view';


interface EtablissementTabProps {
  renderField: (field: FormFieldType<EstablishmentRequest>, options?: RenderFieldOptions) => 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 [managerPersonalEmailAvailibility, setManagerPersonalEmailAvailibility] = useState<{ message: string, isAvailable: boolean } | null>(null);
  const [openInfrastructureModal, setOpenInfrastructureModal] = useState(false);
  const handleAddInfrastructure = () => setOpenInfrastructureModal(true);
  const handleCloseInfrastructureModal = () => setOpenInfrastructureModal(false);
  const {
    existsUserByPersonalEmailLoading,
    existsUserByPersonalEmail
  } = useUserStore();

  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 managerPersonalEmailTimeoutRef = useRef<NodeJS.Timeout>();

  const checkManagerPersonalEmail = useCallback((managerPersonalEmail: string) => {
    if (managerPersonalEmailTimeoutRef.current) {
      clearTimeout(managerPersonalEmailTimeoutRef.current);
    }

    if (!managerPersonalEmail) {
      setManagerPersonalEmailAvailibility(null);
      return;
    }

    const trimmedManagerPersonalEmail = managerPersonalEmail.trim();
    if (trimmedManagerPersonalEmail === '') {
      setManagerPersonalEmailAvailibility(null);
      return;
    }

    managerPersonalEmailTimeoutRef.current = setTimeout(() => {
      const verifyManagerPersonalEmail = async () => {
        try {
          const exists = await existsUserByPersonalEmail(trimmedManagerPersonalEmail);

          setManagerPersonalEmailAvailibility({
            message: exists ? "L'email existe déjà" : "L'email est disponible",
            isAvailable: !exists
          });
        } catch (error) {
          setManagerPersonalEmailAvailibility(null);
        }
      };

      verifyManagerPersonalEmail();
    }, 500);
  }, [mode, existsUserByPersonalEmail]);

  useEffect(() => {
    return () => {
      if (managerPersonalEmailTimeoutRef.current) {
        clearTimeout(managerPersonalEmailTimeoutRef.current);
      }
    };
  }, []);

  const renderFieldResponsable = (field: FormFieldType<EstablishmentManager>) => (
    <>
      <FormField
        field={field}
        value={values.establishmentManager?.[field.name]}
        onChange={(name, value) => {
          setFieldValue(`establishmentManager.${name}`, value);
          if (field.name === 'personalEmail') {
            checkManagerPersonalEmail(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}` } })}
      />
      <ConditionalComponent isValid={field.name === 'personalEmail'}>
        <FormHelperText
          sx={{
            color: existsUserByPersonalEmailLoading ? 'text.secondary' : (managerPersonalEmailAvailibility?.isAvailable ? 'success.main' : 'error.main'),
            marginTop: '4px',
            display: 'flex',
            alignItems: 'center'
          }}
        >
          <ConditionalComponent isValid={existsUserByPersonalEmailLoading}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Box
                sx={{
                  width: '16px',
                  height: '16px',
                  border: '2px solid #f3f3f3',
                  borderTop: '2px solid #746CD4',
                  borderRadius: '50%',
                  animation: 'spin 1s linear infinite',
                  marginRight: '8px',
                  '@keyframes spin': {
                    '0%': { transform: 'rotate(0deg)' },
                    '100%': { transform: 'rotate(360deg)' }
                  }
                }}
              />
              <Typography sx={{ color: '#746CD4' }}>
                Vérification en cours...
              </Typography>
            </Box>
          </ConditionalComponent>
          <ConditionalComponent isValid={!existsUserByPersonalEmailLoading}>
            {managerPersonalEmailAvailibility?.message}
          </ConditionalComponent>
        </FormHelperText>
      </ConditionalComponent>
    </>
  );

  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, { onAddInfrastructure: handleAddInfrastructure })}
            </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>
      <CreateInfrastructureModal
        open={openInfrastructureModal}
        onClose={handleCloseInfrastructureModal}
        PaperProps={{
          style: {
            height: '90vh',
            width: '80%',
            maxWidth: 'none',
          },
        }}
      />
    </>
  );
}
