'use client';

import React, { useMemo } from 'react';
import { Grid } from '@mui/material';
import { FormFieldType } from '@/shared/types/common';
import { IRepresentative } from '@/shared/types/usager';
import { INITIAL_REPRESENTATIVE_DATA } from '@/shared/_mock/_represantative';
import { interlocuteursFormFields } from '../../utils/form-fields-representative';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import { centerFlexColumn } from '@/shared/theme/css';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { useFormik } from 'formik';
import { otherInterlocutorsSchema } from '../../utils/usager-validation';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';



export default function AutresInterlocuteursForm() {
  const formik = useFormik<IRepresentative>({
    initialValues: INITIAL_REPRESENTATIVE_DATA,
    validationSchema: otherInterlocutorsSchema,
      onSubmit: (values) => {
        setIsReadOnly(true);
    },
  });

  const [isReadOnly, setIsReadOnly] = React.useState(true);

  const handleEdit = () => {
    setIsReadOnly(false);
  };

  const handleSave = () => {
    formik.validateForm().then((errors) => {
      formik.submitForm();
    });
  };

  const handleCancel = () => {
    formik.resetForm();
    setIsReadOnly(true);
  };

  const memoizedFormFields = useMemo(() => {
    const renderField = (field: FormFieldType<IRepresentative>) => {
      const error = formik.touched[field.name] ;
      return (
        <FormField
          field={field}
          value={formik.values[field.name]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={error ? (formik.errors[field.name as keyof IRepresentative] as string | undefined)
            : undefined}
          isReadOnly={isReadOnly}
          onBlur={formik.handleBlur}
        />
      );
    };
    return (
      <>
        {interlocuteursFormFields.map((field) => (
          <Grid item sx={centerFlexColumn} xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </>
    );
  }, [formik, isReadOnly]);

  return (
    <>
    <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
        onEdit={handleEdit}
        onExport={() => void 0}
        tooltipTitle="l'interlocuteur"
        />
      </ConditionalComponent>
      <Grid container spacing={4} sx={{ pt: 2 }}>
        {memoizedFormFields}
      </Grid>
      <ConditionalComponent isValid={!isReadOnly}>
        <Grid item xs={12} sx={{ mt: 2, pt: 'calc(100vh - 803px)' }}>
          <ActionButtons onSave={handleSave} onCancel={handleCancel} />
        </Grid>
      </ConditionalComponent>
    </>
  );
}
