'use client';

import React, { useEffect, useState } from 'react';
import {
  Box,
  Grid,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  IconButton,
} from '@mui/material';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { fr } from 'date-fns/locale';
import { useFormik } from 'formik';
import { IRole, RoleModule, RolePayload } from '@/shared/types/role';
import { ScrollBox } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { ModeType } from '@/shared/types/common';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { formFields } from '../utils/form-fields-role';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import ModuleSelector from '../components/ModuleSelector';
import { MOCK_MENU_ITEMS } from '@/shared/_mock/_modules';
import { IconDefinition } from '@fortawesome/fontawesome-svg-core';
import { ModuleFormData } from '@/shared/types/ModuleFormData';
import ModulesRoleList from '../components/ModulesRoleList';
import { RoleStatus, useRoleStore } from '@/shared/api/stores/roleStore';
import { getKeysByValues, resolveModulePermissions, UiAction } from '../utils/logic-permission-handling';
import { Permission } from '@/shared/types/permission';
import { useSnackbar } from 'notistack';
import { roleSchema } from '../utils/role-schema';

interface RoleFormProps {
  role: IRole;
  mode: ModeType;
  onSave: (updatedRole: IRole) => void;
  onEdit: (role: IRole) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, content: IRole) => void;
  tabId: string;
}

export default function RoleForm({
  role,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: RoleFormProps) {
  const { createRole, updateRole } = useRoleStore();
  const [openModuleSelector, setOpenModuleSelector] = useState(false);
  const isReadOnly = mode === 'view';
  const [editingModuleIndex, setEditingModuleIndex] = useState<number | null>(null);
  const [moduleToEdit, setModuleToEdit] = useState<ModuleFormData | null>(null);
  const { enqueueSnackbar } = useSnackbar();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const formik = useFormik<IRole>({
    initialValues: {
      ...role,
      modules: role.modules || [],
      status: role.status as RoleStatus,
    },
    validationSchema: roleSchema,
    onSubmit: async (values) => {
      setIsSubmitting(true);

      try {
        let permissions: Permission[] = [];
        values.modules.forEach((moduleData) => {
          const moduleLabel = moduleData.module;
          const actions = moduleData.permissions as UiAction[];
          const resolvedPermissions = resolveModulePermissions(moduleLabel, actions);
          permissions.push(...resolvedPermissions);
        });

        const roleData = {
          ...values,
          permissions: getKeysByValues(permissions)
        };

        if (mode === 'add') {
          try {
            await createRole(roleData);
            enqueueSnackbar('Rôle créé avec succès', { variant: 'success' });
            onClose(true);
          } catch (error: any) {
            enqueueSnackbar(error.message, { variant: 'error' });
            return;
          }

        } else if (mode === 'edit') {
          try {
            await updateRole(role.id, roleData);
            enqueueSnackbar('Rôle modifié avec succès', { variant: 'success' });
            onClose(true);
          } catch (error: any) {
            enqueueSnackbar(error.message, { variant: 'error' });
            return;
          }
        }

      } catch (error) {
        enqueueSnackbar('Erreur lors de la sauvegarde', { variant: 'error' });
      }
    },
  });



  const handleModuleAdd = (newModule: ModuleFormData) => {
    if (editingModuleIndex !== null) {
      // Mode édition: remplacer le module existant
      const updatedModules = [...formik.values.modules || []];
      updatedModules[editingModuleIndex] = newModule;
      formik.setFieldValue('modules', updatedModules);
      setEditingModuleIndex(null);
      setModuleToEdit(null);
    } else {
      // Mode ajout: ajouter un nouveau module
      formik.setFieldValue('modules', [...formik.values.modules || [], newModule]);
    }
    setOpenModuleSelector(false);
  };

  const handleEditModule = (index: number, module: ModuleFormData) => {
    setEditingModuleIndex(index);
    setModuleToEdit(module);
    setOpenModuleSelector(true);
  };

  const handleCancel = () => {
    formik.resetForm();
    onClose(false);
  };

  // Enhanced save handler that properly manages unsaved changes
  const handleSave = async () => {
    try {
      // Set submitting state to prevent unsaved changes detection
      setIsSubmitting(true);
      await formik.submitForm();
    } catch (error) {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    console.log(formik.values);

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

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <ScrollBox sx={{ pt: 0, backgroundColor: 'white' }}>
        <Box sx={{ p: 3, pb: 0, backgroundColor: 'white' }}>
          <ConditionalComponent isValid={isReadOnly}>
            <EditExportButtons
              onEdit={() => onEdit(role)}
              onExport={() => { }}
              tooltipTitle="le rôle"
            />
          </ConditionalComponent>

          <form onSubmit={formik.handleSubmit}>
            <Grid container spacing={3}>
              {formFields.map((field) => {
                if (field.type === 'custom' && field.name === 'modules') {
                  return (
                    <Grid item xs={12} sm={6} key={field.name}>
                      <Button
                        variant="outlined"
                        onClick={() => {
                          setEditingModuleIndex(null);
                          setModuleToEdit(null);
                          setOpenModuleSelector(true);
                        }}
                        startIcon={field.icon && <FontAwesomeIcon icon={field.icon as IconDefinition} />}
                        fullWidth
                        disabled={isReadOnly || isSubmitting}
                        sx={{
                          color: '#8270C4',
                          borderColor: '#8270C4',
                          '&:hover': {
                            backgroundColor: 'rgba(130, 112, 196, 0.08)',
                            borderColor: '#8270C4',
                          },
                          height: '56px',
                          borderRadius: '8px',
                          textTransform: 'none',
                          fontSize: '16px',
                        }}
                      >
                        Ajouter un module
                      </Button>
                    </Grid>
                  );
                }

                if (field.name === 'modules') {
                  return (
                    <Grid item xs={12} sm={6} key={field.name}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Box sx={{ flex: 1 }}>
                          <FormField
                            field={field}
                            value={formik.values[field.name as keyof IRole]}
                            onChange={(name, value) => formik.setFieldValue(name, value)}
                            error={
                              formik.touched[field.name as keyof IRole]
                                ? (formik.errors[field.name as keyof IRole] as string | undefined)
                                : undefined
                            }
                            onBlur={formik.handleBlur}
                            isReadOnly={isReadOnly}
                          />
                        </Box>
                        <ConditionalComponent isValid={!isReadOnly}>
                          <IconButton
                            onClick={() => setOpenModuleSelector(true)}
                            disabled={isSubmitting}
                            sx={{
                              color: '#8270C4',
                              '&:hover': {
                                backgroundColor: 'rgba(130, 112, 196, 0.08)',
                              },
                            }}
                          >
                            <AddCircleOutlineIcon />
                          </IconButton>
                        </ConditionalComponent>
                      </Box>
                    </Grid>
                  );
                }

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

            <ConditionalComponent isValid={!isReadOnly}>
              <Box sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end' }}>
                <ActionButtons
                  onSave={handleSave}
                  onCancel={handleCancel}
                  mode={mode}
                />
              </Box>
            </ConditionalComponent>
          </form>
        </Box>

        <ConditionalComponent isValid={isReadOnly}
          defaultComponent={
            <Box sx={{ backgroundColor: 'white', p: 3, pt: 0 }}>
              <ModulesRoleList
                modules={formik.values.modules || []}
                menuItems={MOCK_MENU_ITEMS}
                onDelete={(index: number) => {
                  const newModules = [...formik.values.modules || []];
                  newModules.splice(index, 1);
                  formik.setFieldValue('modules', newModules);
                }}
                onEdit={handleEditModule}
              />
            </Box>
          }
        >
          <Box sx={{ backgroundColor: 'white', p: 3, pt: 0 }}>
            <ModulesRoleList
              modules={formik.values.modules || []}
              menuItems={MOCK_MENU_ITEMS}
              onDelete={() => { }}
              isReadOnly={true}
            />
          </Box>
        </ConditionalComponent>
      </ScrollBox>

      <ModuleSelector
        open={openModuleSelector}
        onClose={() => {
          setOpenModuleSelector(false);
          setEditingModuleIndex(null);
          setModuleToEdit(null);
        }}
        onSave={handleModuleAdd}
        menuItems={MOCK_MENU_ITEMS}
        editModule={moduleToEdit}
      />
    </LocalizationProvider>
  );
}