import React, { useEffect, useMemo, useState } from 'react';
import { Grid, Typography, Avatar } from '@mui/material';

import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp, faUser } from '@fortawesome/free-solid-svg-icons';
import { centerFlexColumn } from '@/shared/theme/css';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import { INITIAL_USAGER_DATA } from '@/shared/_mock/_usagers';
import {
  getPassengerFormFields,
  passengerFormFieldsSecondary,
} from '../../utils/form-fields-usager';
import { Box } from '@mui/system';
import { AddButton } from '@/shared/components/table/styles';
import ScheduleTable from '@/shared/components/form/schedule-table';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import AvatarUploader from '@/shared/components/form/avatar-uploader';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { IPassengerList } from '@/shared/types/passenger';
import { useEstablishmentStore } from '@/shared/api/stores/admin-service/establishmentStore';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';

interface UsagerTabContentProps {
  renderField: (field: FormFieldType<IPassengerList>) => React.ReactNode;
  usager: IPassengerList;
  onEdit: (updatedContract: IPassengerList) => void;
  handleSave: () => void;
  onClose: (isSaved: boolean) => void;
  mode: ModeType;
  tableHead: TableColumn[];
}

export default function UsagerTabForm({
  renderField,
  usager,
  onEdit,
  handleSave,
  onClose,
  mode,
  tableHead
}: UsagerTabContentProps) {
  const isReadOnly = mode === 'view';
  const { establishments, fetchEstablishmentsPage } = useEstablishmentStore();
  const {
    departmentNames,
    fetchDepartmentNames,
  } = useInfrastructureStore();

  const [establishmentOptions, setEstablishmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([]);

  useEffect(() => {
    fetchEstablishmentsPage();
    fetchDepartmentNames();
  }, [fetchDepartmentNames, fetchEstablishmentsPage]);

  useEffect(() => {
    if (establishments.length > 0) {
      setEstablishmentOptions(establishments.map((establishment) => ({
        value: String(establishment.id),
        label: establishment.establishmentName
      })));
    }
  }, [establishments]);

  useEffect(() => {
    if (departmentNames.length > 0) {
      setDepartmentOptions(departmentNames.map((department) => ({
        value: String(department.id),
        label: department.name
      })));
    }
  }, [departmentNames]);

  const memoizedFormFields = useMemo(() => {
    return (
      <>
        <Grid item xs={12}>
          <AvatarUploader onUpload={() => void 0} isReadOnly={isReadOnly} />
        </Grid>
        {getPassengerFormFields(establishmentOptions, departmentOptions).map((field) => (
          <Grid sx={centerFlexColumn} item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
        <Grid sx={centerFlexColumn} item xs={12} sm={4} key="document">
          <Box display="flex" alignItems="center" gap={4}>
            <Typography sx={{ color: isReadOnly ? "text.disabled" : "primary.main" }}>
              Importer document
            </Typography>
            <AddButton
              sx={{ p: 1 }}
              disabled={isReadOnly}
              variant="contained"
              endIcon={<FontAwesome icon={faFileArrowUp} />}
            >
              Importez un document
            </AddButton>
          </Box>
        </Grid>
        {passengerFormFieldsSecondary.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </>
    );
  }, [isReadOnly, renderField]);

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(usager)}
          onExport={() => void 0}
          tooltipTitle={TableType.Usager}
          dataRow={usager}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <Grid container spacing={4} sx={{ pt: 2 }}>
        {memoizedFormFields}
      </Grid>
      <ConditionalComponent defaultComponent={<ScheduleTable title="Emploi du temps" mode="time" />} isValid={!isReadOnly} >
        <Grid item xs={12} sx={{ mt: 2 }}>
          <ActionButtons onSave={handleSave} onCancel={() => onClose(false)} mode={mode} />
        </Grid>
      </ConditionalComponent>
    </>
  );
}
