'use client';

import React, { useEffect, useMemo } from 'react';
import { Grid, IconButton, InputAdornment } from '@mui/material';
import { centerFlexColumn, StyledTextField } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { IRHAbsence } from '../../../../types/absence-rh';
import { _TYPES_ABSENCE, _MODES_RECEPTION } from '@/shared/_mock/_rhAbsence';
import { createFormFieldsRHAbsence } from '../utils/form-fields-rh-absence';
import { useResponsive } from '@/hooks';
import { faPaperclip } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { useFormik } from 'formik';
import { absenceSchema } from '../utils/absence-schema';
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

export interface RHAbsenceFormProps {
  absence: IRHAbsence;
  mode: ModeType;
  onSave: (updatedAbsence: IRHAbsence) => void;
  onEdit: (updatedAbsence: IRHAbsence) => void;
  onClose: (forceClose: boolean) => void;
  isTraiteAbsence?: boolean;
  updateTabContent?: (tabId: string, newContent: IRHAbsence) => void;
  tabId?: string;
}

export default function AbsenceForm({
  absence,
  mode,
  onSave,
  onClose,
  onEdit,
  isTraiteAbsence,
  updateTabContent,
  tabId,
}: RHAbsenceFormProps) {
  const isBetweenSmAndLg = useResponsive('between', 'sm', 'lg');
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const isReadOnly = mode === 'view';

  const formik = useFormik<IRHAbsence>({
    initialValues: absence,
    validationSchema: absenceSchema,
    enableReinitialize: true,
    onSubmit: (values) => {
      onSave(values); 
      onClose(true);
    },
  });

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

  const formFields = useMemo(() => createFormFieldsRHAbsence(), []);

  const handleIconClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      formik.setFieldValue('justificatif', file.name);
    }
  };
  
  const renderField = (field: FormFieldType<IRHAbsence>) => {
    const fieldValue = formik.values[field.name as keyof IRHAbsence];
    const error = formik.touched[field.name as keyof IRHAbsence] && formik.errors[field.name as keyof IRHAbsence];
    
    if (field.name === 'justificatif') {
      return (
        <StyledTextField
          isSmallScreen={isBetweenSmAndLg}
          fullWidth
          name={field.name}
          InputLabelProps={{
            shrink: true,
          }}
          value={fieldValue || ''}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={!!error}
          helperText={error as string}
          label={field.label}
          placeholder={field.placeholder}
          sx={{
            ...(isReadOnly && {
              '& .MuiInputBase-root': {
                backgroundColor: '#f5f5f5',
                cursor: 'not-allowed',
              },
              '& .MuiInputBase-input': {
                cursor: 'not-allowed',
                color: 'text.disabled',
              }
            })
          }}
          InputProps={{
            readOnly: isReadOnly,
            endAdornment: (
              <InputAdornment position="end">
                <CustomTooltip title="Importer la justification" arrow>
                  <IconButton onClick={handleIconClick} disabled={isReadOnly}> 
                    <FontAwesome
                      icon={faPaperclip}
                      sx={{
                        color: isReadOnly ? 'text.disabled' : "primary.main",
                        width: isBetweenSmAndLg ? 16 : 18,
                      }}
                    />
                  </IconButton>
                </CustomTooltip>
              </InputAdornment>
            ),
          }}
        />
      );
    }
    
    return (
      <FormField
        field={field}
        value={fieldValue}
        onChange={(name, value) => formik.setFieldValue(name, value)}
        error={error as string}
        onBlur={formik.handleBlur}
        isReadOnly={field.name === 'affecteTrajet' || field.name === 'departement' ? true : isReadOnly}
      />
    );
  };
  
  return (
    <FormContainer titre="Fiche Absence">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={isTraiteAbsence ? undefined : () => onEdit(formik.values)}
          onExport={() => void 0}
          tooltipTitle="l'absence"
        />
      </ConditionalComponent>
      
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {formFields.map((field) => (
            <Grid 
              item 
              xs={12} 
              sx={field.name === 'affecteTrajet' ? centerFlexColumn : undefined} 
              sm={4} 
              key={field.name}
            >
              {renderField(field)}
            </Grid>
          ))}

          <input type="file" ref={fileInputRef} style={{ display: 'none' }} onChange={handleFileUpload} />

          <Grid item xs={12}>
            <ConditionalComponent isValid={mode !== 'view'}>
              <ActionButtons 
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm();
                  });
                }}
                onCancel={() => onClose(false)}
                mode={mode}
              />
            </ConditionalComponent>
          </Grid>
        </Grid>
      </form>
    </FormContainer>
  );
} 