'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';

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 default function ClientForm({
  client,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  updateTabContent,
  tabId
}: ClientFormProps) {
  const isReadOnly = mode === 'view';
  const copyFieldsToClear = ['firstName', 'lastName', 'email', 'password', 'civility', 'landlinePhone', 'phoneNumber'];

  const getInitialValues = (client: IClient, mode: ModeType): IClient => {
    if (mode !== 'copy') return client;
    const clearedClient = { ...client };
    copyFieldsToClear.forEach((field) => {
      (clearedClient as any)[field] = '';
    });
  
    return clearedClient;
  };
   const formik = useFormik<IClient>({
    initialValues: getInitialValues(client, mode),
    validationSchema: clientSchema,
    onSubmit: (values) => {
      onSave(values)
      onClose(true);
    },
  });

  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) => (
            <RenderField field={field} formik={formik} client={client} mode={mode} />
          )}
          client={client}
          mode={mode}
          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>
  );
}
