'use client';

import React, { useCallback, useMemo, useState } from 'react';
import { Grid, Button, IconButton } from '@mui/material';
import { FormFieldType } from '@/shared/types/common';
import { IRepresentative, SelectedDaysType } from '@/shared/types/usager';
import FormField from '@/shared/components/form/form-field';
import ScheduleTable from '@/shared/components/form/schedule-table';
import FontAwesome from '@/shared/components/fontawesome';
import {
  faAnglesDown,
  faAnglesUp,
  faPenToSquare,
} from '@fortawesome/free-solid-svg-icons';
import {
  contactFormFields,
  mainRepresentantformFields,
} from '../../../utils/form-fields-representative';
import { Box } from '@mui/system';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { centerFlexColumn, iconButtonStyles } from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import { FieldType, useMultipleFields } from '@/hooks/use-multiple-fields';
import DuplicableField from '@/shared/components/form/duplicable-field';
import { useFormik } from 'formik';
import { representativeSchema } from '../../../utils/usager-validation';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface RepresentantFormProps {
  data: IRepresentative;
  isReadOnly: boolean;
  withContact?: boolean;
  onChange: (newData: Partial<IRepresentative>) => void;
  handleEdit?: () => void;
  handleTabClose: (event: React.MouseEvent) => void;
  onSave: () => void;
}

export default function RepresentantForm({
  data,
  isReadOnly,
  onChange,
  handleEdit,
  handleTabClose,
  onSave,
  withContact,
}: RepresentantFormProps) {
  const [selectedDays, setSelectedDays] = useState<SelectedDaysType>(data.schedule || {});
  const [isReduced, setIsReduced] = useState(true);

  const formik = useFormik<IRepresentative>({
    initialValues: data,
    validationSchema: representativeSchema,
    onSubmit: (values) => {
      onChange(values);
      onSave();
    },
  });

  const { fields, handleAdd, handleDelete, handleChange } = useMultipleFields({
    initialValues: {
      mobile: data.mobile || [''],
      fixe: data.fixe || [''],
      personne: data.personne || [''],
    },
    onChange: (type, newValues) => {
      formik.setFieldValue(type, newValues);
    },
    isReadOnly,
  });

  const handleSelectionChange = useCallback(
    ({
      week,
      day,
      type,
      checked,
    }: {
      week: 'pair' | 'impair';
      day: string;
      type: 'all' | 'ret';
      checked: boolean;
    }) => {
      if (!isReadOnly) {
        const newSchedule = {
          ...selectedDays,
          [week]: {
            ...selectedDays[week],
            [day]: {
              ...selectedDays[week]?.[day],
              [type]: checked,
            },
          },
        };
        setSelectedDays(newSchedule);
        formik.setFieldValue('schedule', newSchedule);
      }
    },
    [isReadOnly, selectedDays, formik]
  );

  const renderField = useCallback(
    (field: FormFieldType<IRepresentative>) => {
      const error = formik.touched[field.name] && formik.errors[field.name];
      return (
        <FormField
          field={field}
          value={formik.values[field.name]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={error ?
            field.name==="address" || field.name==="adresseEtablissement" ? (formik.errors.address as any)?.address
            :
            String(formik.errors[field.name])
             : undefined}
          isReadOnly={isReadOnly}
          isDrawerElement={true}
          onBlur={formik.handleBlur}
        />
      );
    },
    [formik, isReadOnly]
  );

  const memoizedFormFields = useMemo(() => {
    return (
      <>
        {mainRepresentantformFields.map((field) => (
          <Grid
            item
            xs={12}
            sx={centerFlexColumn}
            sm={field.name === 'civilite' ? 8 : 4}
            key={field.name}
          >
            {renderField(field)}
          </Grid>
        ))}
      </>
    );
  }, [renderField]);

  const lastFormFields = useMemo(() => {
    const fieldsToRender = !withContact
      ? contactFormFields.slice(3).filter((field) => field.name === "circuit" || field.name === "adresseEtablissement")
      : contactFormFields.slice(3)

    return (
      <>
        {fieldsToRender.map((field) => (
          <Grid item xs={12} sm={field.name === "notificationArivee" ? 6 : 4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </>
    )
  }, [renderField, withContact])

  const renderPhoneFields = useMemo(() => {
    return ['mobile', 'fixe', 'personne'].map((type) => {
      const numbers = fields[type as FieldType] || [];
      const field = contactFormFields.find((f) => f.name === type);
      return numbers.map((number, index) => {
        const fieldName = `${type}.${index}`;
        const error = formik.touched[field?.name as keyof IRepresentative] && formik.errors[field?.name as keyof IRepresentative];
        return (
          <DuplicableField
            key={`${type}-${index}`}
            fieldType={type as FieldType}
            field={field!}
            index={index}
            value={number}
            isReadOnly={isReadOnly}
            onChange={handleChange}
            onAdd={handleAdd}
            onDelete={handleDelete}
            sx={{ display: "flex", flexDirection: "column" }}
            formData={formik.values}
            error={error ? String(formik.errors[field?.name as keyof IRepresentative]) : undefined}
            onBlur={() => formik.setFieldTouched(fieldName, true)}
          />
        );
      });
    });
  }, [fields, isReadOnly, handleAdd, handleDelete, handleChange, formik]);

  const handleToggleReduced = useCallback(() => {
    setIsReduced((prev) => !prev);
  }, []);

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    formik.validateForm().then((errors) => {
      formik.submitForm();
    });
  };

  return (
    <Box
      sx={{
        width: '100%',
        mb: 2,
        height: isReduced ? '80px' : 'auto',
        overflow: isReduced ? 'hidden' : 'visible',
      }}
    >
      <Box sx={{ position: 'absolute', bottom: 0, right: 0 }}>
        <Button
          endIcon={<FontAwesome icon={isReduced ? faAnglesDown : faAnglesUp} width={12} />}
          onClick={handleToggleReduced}
          variant="text"
          sx={{
            textTransform: 'none',
            fontSize: pxToRem(13),
            '&:hover': {
              backgroundColor: 'transparent',
            },
          }}
        >
          {isReduced ? 'Voir plus' : 'Réduire détails'}
        </Button>
      </Box>
      <ConditionalComponent isValid={isReadOnly && !!handleEdit && !isReduced}>
        <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 1 }}>
          <CustomTooltip title="Modifier Adresse" arrow>
            <IconButton sx={iconButtonStyles} onClick={handleEdit}>
              <FontAwesome icon={faPenToSquare} width={15} />
            </IconButton>
          </CustomTooltip>
        </Box>
      </ConditionalComponent>

      <form onSubmit={handleFormSubmit}>
        <Grid container spacing={2} sx={{ pt: 2 }}>
          {memoizedFormFields}
        </Grid>

        <ConditionalComponent isValid={!!withContact}>
          <Grid container spacing={2} sx={{ pt: 3 }}>
            {renderPhoneFields}
          </Grid>
        </ConditionalComponent>

        <Grid container spacing={2} sx={{ pt: 2 }}>
          {lastFormFields}
        </Grid>
        <ScheduleTable
          title="Trajets concernés"
          mode="checkbox"
          selectedDays={selectedDays}
          onSelectionChange={handleSelectionChange}
          isRepresentative={true}
        />

        <ConditionalComponent isValid={!isReadOnly && !!handleEdit}>
          <Grid item xs={12} sx={{ pt: 2 }}>
            <Box display="flex" justifyContent="flex-end" gap={2}>
              <Button
                variant="outlined"
                onClick={handleTabClose}
                sx={{
                  fontSize: pxToRem(13),
                  textTransform: "none",
                  borderColor: (theme) => theme.palette.primary.main,
                  color: (theme) => theme.palette.primary.main,
                  "&:hover": {
                    backgroundColor: "rgba(107, 78, 255, 0.04)",
                  },
                }}
              >
                Annuler
              </Button>
              <Button
                onClick={handleFormSubmit}
                variant="contained"
                sx={{
                  boxShadow: "none",
                  fontSize: pxToRem(13),
                  textTransform: "none",
                  backgroundColor: (theme) => theme.palette.primary.main,
                  "&:hover": {
                    backgroundColor: (theme) => theme.palette.primary.dark,
                  },
                }}
              >
                Enregistrer
              </Button>
            </Box>
          </Grid>
        </ConditionalComponent>
      </form>
    </Box>
  )
}
