'use client';

import React, { useEffect } from 'react';
import {
  Box,
  Grid,
  Typography,
} from '@mui/material';
import {
  faHashtag,
} from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import { ICircuitContract } from '@/shared/types/circuit';
import SvgColor from '@/shared/components/svg-color';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';
import { formFieldsCircuitContrat } from '../../../utils/form-fields-circuit';
import { tabsBorder } from '@/shared/theme/css';
import { useFormik } from 'formik';
import { circuitContractSchema } from '../../../utils/circuit-validation';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface ContratFormProps {
  contrat: ICircuitContract;
  mode: ModeType;
  onSave: (updatedTrajet: ICircuitContract) => void;
  onEdit: (updatedTrajet: ICircuitContract) => void;
  onClose: () => void;
  setHasUnsavedChanges: (value: boolean) => void
  updateTabContent: (tabId: string, content: ICircuitContract) => void
  tabId: string
}

export default function NewContratForm({
  contrat,
  mode,
  onSave,
  onClose,
  onEdit,
  setHasUnsavedChanges,
  updateTabContent,
  tabId
}: ContratFormProps) {
  const popover = usePopover();
  const isReadOnly = mode === 'view';

  const formik = useFormik<ICircuitContract>({
    initialValues: contrat,
    validationSchema: circuitContractSchema,
    onSubmit: (values) => {
      onSave(values);
      setHasUnsavedChanges(false)
      onClose();
    },
    enableReinitialize: true
  });
  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])
  const renderFieldCircuitContrat = (field: FormFieldType<ICircuitContract>) => {
    const error = formik.touched[field.name] && formik.errors[field.name];
    return (
      <>
        <FormField
          field={field}
          openPopover={popover.onOpen}
          value={formik.values[field.name]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={error ? String(formik.errors[field.name]) : undefined}
          isReadOnly={isReadOnly}
          onBlur={formik.handleBlur}
        />
  <ConditionalComponent isValid={field.name === "contrat"}>
          <CustomPopover
            arrow="top-right"
            hiddenArrow={true}
            open={popover.open}
            onClose={popover.onClose}
            sx={{
              borderRadius: 4,
              p: 1,
              px: 2,
            }}
          >
            <Box sx={{ py: 0.5, display: "flex", alignItems: "center", gap: 1 }}>
              <SvgColor
                src="/assets/icons/form/ic_file_contrat.svg"
                sx={{ width: 16, height: 16, color: "primary.main" }}
              />
              <Typography variant="body2">{formik.values.contrat}</Typography>
            </Box>
            <Box sx={{ py: 0.5, display: "flex", alignItems: "center", gap: 1 }}>
              <FontAwesome icon={faHashtag} width={16} sx={{ color: "primary.main" }} />
              <Typography variant="body2">{formik.values.numeroContrat}</Typography>
            </Box>
            <Box sx={{ py: 0.5, display: "flex", alignItems: "center", gap: 1 }}>
              <SvgColor
                src="/assets/icons/menu/ic_exploitation.svg"
                sx={{ width: 16, height: 16, color: "primary.main" }}
              />
              <Typography variant="body2">{formik.values.circuit}</Typography>
            </Box>
          </CustomPopover>
        </ConditionalComponent>
      </>
    );
  };

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

  return (
    <Box sx={tabsBorder}>
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={6} sx={{ py: 2 }}>
          {formFieldsCircuitContrat.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderFieldCircuitContrat(field)}
            </Grid>
          ))}
        </Grid>
        <ConditionalComponent isValid={!isReadOnly}>
          <Grid item xs={12}>
            <ActionButtons onSave={handleSave} onCancel={onClose} />
          </Grid>
        </ConditionalComponent>
      </form>
    </Box>
  );
}
