import React, { useEffect, useState } from "react"
import { Grid, Button } from "@mui/material"
import { formFields } from "../utils/form-fields-client"
import { centerFlexColumn } from "@/shared/theme/css"
import { TableType, type FormFieldType, type ModeType, type TableColumn } from "@/shared/types/common"
import type { IClient } from "@/shared/types/client"
import ActionButtons from "@/shared/components/form/buttons-action"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { useAgencyStore } from "@/shared/api/stores/agencyStore"
import { useClientStore } from "@/shared/api/stores/userStore"
import CreateInfrastructureModal from "@/shared/components/dialog/create-infrastructure-modal"

export interface RenderFieldOptions {
  onAddInfrastructure?: () => void;
}
interface ClientTabProps {
  renderField: (field: FormFieldType<IClient>,options?: RenderFieldOptions) => React.ReactNode
  mode: ModeType
  onSave: () => void
  onClose: () => void
  onEdit: () => void
  client: IClient
  tableHead: TableColumn[];
  departmentOptions: { label: string; value: string }[];
}

export default function ClientTab({ mode, onSave, onClose, onEdit, renderField, tableHead, client, departmentOptions }: ClientTabProps) {
  const isReadOnly = mode === "view"
  const { agenciesName, loading, error, fetchAgenciesName } = useAgencyStore();
  const [agencyOptions, setAgencyOptions] = useState<{ label: string; value: string }[]>([]);
  const [clientTypeOptions, setClientTypeOptions] = useState<{ label: string; value: string }[]>([]);
  const [openInfrastructureModal, setOpenInfrastructureModal] = useState(false);
  const handleAddInfrastructure = () => setOpenInfrastructureModal(true);
  const handleCloseInfrastructureModal = () => setOpenInfrastructureModal(false);



  useEffect(() => {
    fetchAgenciesName();
    // init depuis l'énum côté backend (valeurs fixes)
    setClientTypeOptions([
      { label: "Donneur d'ordre", value: 'CLIENT_DO' },
      { label: 'Autre', value: 'OTHERS' },
    ]);

  }, []);
  useEffect(() => {
    if (agenciesName.length > 0) {
      const options = agenciesName.map((agency) => ({
        label: agency.name,
        value: agency.id.toString(),
      }));
      setAgencyOptions(options);
    }
  }, [agenciesName]);

  // plus de récupération distante pour les types de client
  return (
    <>
      {isReadOnly ? (
        <EditExportButtons
          onEdit={onEdit}
          onExport={() => void 0}
          tooltipTitle={TableType.Client}
          dataRow={client}
          tableHead={tableHead}
        />
      ) : null}

      <form>
        <Grid container spacing={5}>
          {formFields(agencyOptions, clientTypeOptions, departmentOptions).map((field) => (
            <React.Fragment key={field.name}>
              <Grid
                item
                sx={field.name === 'civility' ? centerFlexColumn : undefined}
                xs={12}
                sm={4}
              >
                {renderField(field,{ onAddInfrastructure: handleAddInfrastructure })}
              </Grid>
            </React.Fragment>
          ))}

          {!isReadOnly && (
            <Grid item xs={12}>
              <ActionButtons onSave={onSave} onCancel={onClose} mode={mode} />
            </Grid>
          )}
        </Grid>
      </form>
      <CreateInfrastructureModal
        open={openInfrastructureModal}
        onClose={handleCloseInfrastructureModal}
        PaperProps={{
          style: {
            height: '90vh',
            width: '80%',
            maxWidth: 'none',
          },
        }}
      />
    </>
  )

}

