import React, { useEffect, useState } from "react"
import { Grid } 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"

interface ClientTabProps {
  renderField: (field: FormFieldType<IClient>) => React.ReactNode
  mode: ModeType
  onSave: () => void
  onClose: () => void
  onEdit: () => void
  client: IClient
  tableHead: TableColumn[];
}

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


  useEffect(() => {
    fetchAgenciesName();
    getAllClientTypes();
    
  }, []);
  useEffect(() => {
    if (agenciesName.length > 0) {
      const options = agenciesName.map((agency) => ({
        label: agency.name,
        value: agency.id.toString(),
      }));
      setAgencyOptions(options);
    }
  }, [agenciesName]);
  
  useEffect(() => {
    if (clientTypes.length > 0) {
      const options = clientTypes.map((type) => ({
        label: type.name,
        value: type.id.toString(),
      }));
      setClientTypeOptions(options);
    }
  }, [clientTypes]);
  return (
    <>
     {isReadOnly ? (
        <EditExportButtons
          onEdit={onEdit}
          onExport={() => void 0}
          tooltipTitle={TableType.Client}
          dataRow={client}
          tableHead={tableHead}
        />
      ) : (
        <></>
      )}
      <form>
        <Grid container spacing={5}>
          {formFields(agencyOptions, clientTypeOptions).map((field) => (
            <Grid item sx={field.name === 'civility' ? centerFlexColumn : undefined} xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          {!isReadOnly ? (
            <Grid item xs={12}>
              <ActionButtons onSave={onSave} onCancel={onClose} mode={mode} />
            </Grid>
          ): <></>}
        </Grid>
      </form>
    </>
  )
}

