"use client"

import type React from "react"
import { useFormik } from "formik"
import {
  Grid,
  Stack,
  Button,
} from "@mui/material"
import {
  type INotification,
  DeliveryType,
} from "@/shared/types/notification"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { notificationSchema } from "../utils/notification-schema"
import FormField from "@/shared/components/form/form-field"
import { notificationFormFields } from "../utils/form-fields-notification"
import FormContainer from "@/layouts/form/form-container"
import { FormFieldType, TableType } from "@/shared/types/common"
import { useEffect } from "react"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"

interface NotificationFormProps {
  notification: INotification
  mode: "new" | "edit" | "view"
  onSave: (data: INotification) => void
  onClose: (forceClose: boolean) => void
  onEdit: (id: string) => void
  updateTabContent: (tabId: string, newContent: INotification) => void
  tabId: string
}

export default function NotificationForm({ notification, mode, onSave, onClose, onEdit, updateTabContent, tabId }: NotificationFormProps) {
  const isView = mode === "view"
  const isEdit = mode === "edit"
  const isNew = mode === "new"

  const formik = useFormik<INotification>({
    initialValues: {
      ...notification,
      deliveryType: notification.deliveryType || DeliveryType.IMMEDIAT,
      channels: notification.channels || [],
      recipients: notification.recipients || [],
      isActive: notification.isActive ?? true,
    },
    validationSchema: notificationSchema,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
  });

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const getTitle = (isView: boolean, isEdit: boolean) => {
    if (isView) return "Détails de la notification";
    if (isEdit) return "Modifier la notification";
    return "Créer une notification";
  };

  const renderField = (field: FormFieldType<INotification>) => {
    const shouldShow = !field.showWhen || field.showWhen(formik.values);
    if (!shouldShow) {
      return null;
    }

    return (
      <Grid item xs={12} sm={field.type === 'textarea' ? 12 : 6} key={field.name}>
        <FormField
          field={field}
          value={formik.values[field.name as keyof INotification]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={
            formik.touched[field.name as keyof INotification]
              ? (formik.errors[field.name as keyof INotification] as string | undefined)
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={isView}
          formData={formik.values}
        />
      </Grid>
    );
  };

  return (
    <FormContainer titre={getTitle(isView, isEdit)}>
      <ConditionalComponent isValid={isView}>
        <EditExportButtons
          onEdit={() => onEdit(notification.id)}
          tooltipTitle={TableType.Notification}
        />
      </ConditionalComponent>
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={3}>
          {notificationFormFields.map(renderField)}
        </Grid>

        <Stack direction="row" justifyContent="flex-end" spacing={2} sx={{ mt: 3 }}>
          <Button variant="outlined" color="inherit" onClick={() => onClose(false)}>
            {isView ? "Fermer" : "Annuler"}
          </Button>

            <ConditionalComponent isValid={!isView}>
              <Button
                type="submit"
                variant="contained"
                onClick={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm();
                  });
                }}
              >
                {isEdit ? "Enregistrer" : "Envoyer"}
              </Button>
            </ConditionalComponent>
        </Stack>
      </form>
    </FormContainer>
  );
}
