'use client';

import React, { useEffect, useState } from 'react';
import type { IClient } from '@/shared/types/client';
import FormContainer from '@/layouts/form/form-container';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import ClientTab from '../components/client-tab';
import { AddressData, FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import FormField from '@/shared/components/form/form-field';
import DocumentForm from '@/shared/components/documents/documents-form';
import { _documents } from '@/shared/_mock/_documents';
import { useFormik } from 'formik';
import { clientSchema } from '../utils/client-validation';
import { RenderField } from './render-client-field';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';


interface ClientFormProps {
  client: IClient;
  mode: ModeType;
  onSave: (updatedClient: IClient) => void;
  onEdit: (updatedClient: IClient) => void;
  onClose: (forceClose: boolean) => void;
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, newContent: IClient) => void
  tabId?: string
}
export interface RenderFieldOptions {
  onAddInfrastructure?: () => void;
}
export default function ClientForm({
  client,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  updateTabContent,
  tabId
}: ClientFormProps) {
  const isReadOnly = mode === 'view';
  const copyFieldsToClear = ['firstName', 'lastName', 'email', 'civility', 'landlinePhone', 'phoneNumber'];
  const { getDepartmentHexColorById, departmentNamesByAgencyId, fetchDepartmentNamesByAgencyId } = useInfrastructureStore();
  const [departmentOptions, setDepartmentOptions] = useState<{ label: string; value: string }[]>([]);


  const getInitialValues = (client: IClient, mode: ModeType): IClient => {
    const base = { ...client };
    if (mode === 'add' || mode === 'copy') {
      (base as any)['password'] = 'Pa$$w0rd!';
    }
    if (mode !== 'copy') return base;
    const clearedClient = { ...base };
    copyFieldsToClear.forEach((field) => {
      (clearedClient as any)[field] = '';
    });
    return clearedClient;
  };
  const formik = useFormik<IClient>({
    initialValues: getInitialValues(client, mode),
    validationSchema: clientSchema,
    onSubmit: (values) => {
      const payload = { ...values } as any;
      // En mode view/edit, ne pas envoyer le mot de passe; en add/copy, l'envoyer
      if (!(mode === 'add' || mode === 'copy')) {
        delete payload.password;
      }
      onSave(payload)
      onClose(true);
    },
  });
  useEffect(() => {
    const fetchColor = async () => {
      const departmentId = formik.values.department;
      if (departmentId) {
        try {
          const color = await getDepartmentHexColorById(departmentId.toString());
          formik.setFieldValue('colorCode', color);
        } catch (error) {
          console.error('Failed to fetch department color:', error);
        }
      }
    };

    fetchColor();
  }, [formik.values.department]);

  useEffect(() => {
    const agencyId = Number(mode === 'add' ? (formik.values as any).agencyName : (formik.values as any).agency_id);
    if (agencyId) {
      fetchDepartmentNamesByAgencyId(agencyId);
    } else {
      setDepartmentOptions([]);
    }
  }, [mode, (formik.values as any).agencyName, (formik.values as any).agency_id]);

  useEffect(() => {
    if (departmentNamesByAgencyId && departmentNamesByAgencyId.length > 0) {
      const options = departmentNamesByAgencyId.map((dept) => ({ label: dept.name, value: dept.id.toString() }));
      setDepartmentOptions(options);
    } else {
      setDepartmentOptions([]);
    }
  }, [departmentNamesByAgencyId]);
  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)
      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])




  const tabs = [
    {
      label: 'Client',
      content: (
        <ClientTab
          renderField={(field, options?: RenderFieldOptions) => (
            <RenderField field={field} formik={formik} client={client} mode={mode} onAddInfrastructure={options?.onAddInfrastructure} />
          )}
          client={client}
          mode={mode}
          departmentOptions={departmentOptions}
          onSave={() => {
            formik.validateForm().then((errors) => {
              formik.submitForm();
            });
          }}
          onClose={() => onClose(false)}
          onEdit={() => onEdit(formik.values)}
          tableHead={tableHead}
        />
      ),
    },
    { label: 'Documents', content: <DocumentForm documents={mode === 'add' ? [] : _documents} /> },
  ];

  return (
    <FormContainer titre="Fiche Client">
      <TabbedForm tabs={tabs} />
    </FormContainer>
  );
}
