"use client"

import type React from "react"
import { useEffect, useState } from "react"
import { Box, Grid, Button, 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 type { IRole } 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 type { 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 { MOCK_MENU_ITEMS } from "@/shared/_mock/_modules"
import type { IconDefinition } from "@fortawesome/fontawesome-svg-core"
import type { ModuleFormData } from "@/shared/types/ModuleFormData"
import ModulesRoleList from "../components/ModulesRoleList"
import { type RoleStatus, useRoleStore } from "@/shared/api/stores/roleStore"
import { getKeysByValues, resolveModulePermissions, type UiAction } from "../utils/logic-permission-handling"
import type { Permission } from "@/shared/types/permission"
import { useSnackbar } from "notistack"
import { roleSchema } from "../utils/role-schema"
import ModulePermissionSelector from "../components/PermissionDialogSelector"

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
  onPageChange?: (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => void
}

export default function RoleForm({
  role,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
  onPageChange,
}: 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 {
        const 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 = {
          id: values.id,
          name: values.name,
          description: values.description,
          status: values.status,
          modules:
            mode === "edit" 
              ? (values.modules && values.modules.length > 0 ? values.modules : role.modules) : values.modules,
          permissions:
            mode === "edit"
              ? permissions && Object.keys(permissions).length > 0
                ? getKeysByValues(permissions)
                : role.permissions
              : getKeysByValues(permissions),
        }

        if (mode === "add") {
          try {
            await createRole(roleData)
            enqueueSnackbar("Rôle créé avec succès", { variant: "success" })
            onPageChange?.(null, 0)
            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" })
            onPageChange?.(null, 0)
            onClose(true)
          } catch (error: any) {
            enqueueSnackbar(error.message, { variant: "error" })
            return
          }
        }
      } catch (error) {
        enqueueSnackbar("Erreur lors de la sauvegarde", { variant: "error" })
      }
    },
  })

  const handleModuleAdd = (newModules: ModuleFormData[]) => {
    if (editingModuleIndex !== null) {
      // If editing a single module
      const updatedModules = [...(formik.values.modules || [])]
      updatedModules[editingModuleIndex] = newModules[0]
      formik.setFieldValue("modules", updatedModules)
      setEditingModuleIndex(null)
      setModuleToEdit(null)
    } else {
      // Adding new modules
      const existingModules = formik.values.modules || []
      const combinedModules = [...existingModules, ...newModules]
      formik.setFieldValue("modules", combinedModules)
    }
    setOpenModuleSelector(false)
  }

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

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

  const handleSave = async () => {
    try {
      setIsSubmitting(true)
      await formik.submitForm()
    } catch (error) {
      setIsSubmitting(false)
    }
  }

  useEffect(() => {

    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) => {
                const isFieldDisabled = (mode === "edit" && field.name === "name") || field.name === "createdAt"
                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={isFieldDisabled || 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>

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