'use client';

import { useEffect } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useLanguage } from '@/providers/i18n-provider';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  getRoleFormSchema,
  IRole,
  RoleFormType,
} from '../schemas/role-form-schema';

interface AddRoleModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  role: IRole | null;
  onSave: (role: IRole) => void;
}

const modules = ['users', 'roles', 'requests', 'projects', 'reports'];
const actions = ['view', 'show', 'add', 'update', 'delete'] as const;

export function AddRoleModal({
  open,
  onOpenChange,
  role,
  onSave,
}: AddRoleModalProps) {
  const { t } = useTranslation();
  const { dir } = useLanguage();
  const form = useForm<RoleFormType>({
    resolver: zodResolver(getRoleFormSchema(t)) as any,
    defaultValues: {
      name: '',
      permissions: modules.reduce((acc, module) => {
        acc[module] = {
          view: false,
          show: false,
          add: false,
          update: false,
          delete: false,
        };
        return acc;
      }, {} as any),
    },
  });

  useEffect(() => {
    if (role) {
      form.reset({
        name: role.name,
        permissions: role.permissions,
      });
    } else {
      form.reset({
        name: '',
        permissions: modules.reduce((acc, module) => {
          acc[module] = {
            view: false,
            show: false,
            add: false,
            update: false,
            delete: false,
          };
          return acc;
        }, {} as any),
      });
    }
  }, [role, form, open]);

  const onSubmit = (data: RoleFormType) => {
    onSave({
      id: role?.id || '',
      ...data,
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl" dir={dir}>
        <DialogHeader>
          <DialogTitle className="rtl:text-right">
            {role
              ? t('admin.rolesManagement.updateRole')
              : t('admin.rolesManagement.addRole')}
          </DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit) as any}
            className="space-y-6"
          >
            <FormField
              control={form.control as any}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="rtl:text-right block">
                    {t('admin.rolesManagement.form.roleName')}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t('admin.rolesManagement.form.roleName')}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage className="rtl:text-right" />
                </FormItem>
              )}
            />

            <div className="space-y-4">
              <FormLabel className="rtl:text-right block">
                {t('admin.rolesManagement.form.permissions')}
              </FormLabel>
              <div className="border rounded-lg overflow-hidden">
                <table className="w-full text-sm text-left rtl:text-right">
                  <thead className="bg-muted text-muted-foreground font-medium border-b">
                    <tr>
                      <th className="p-3">
                        {t('admin.rolesManagement.form.modules')}
                      </th>
                      {actions.map((action) => (
                        <th key={action} className="p-3 text-center capitalize">
                          {t(`admin.rolesManagement.actions.${action}`)}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {modules.map((moduleName) => (
                      <tr
                        key={moduleName}
                        className="hover:bg-muted/50 transition-colors"
                      >
                        <td className="p-3 font-medium">
                          {t(`admin.rolesManagement.modules.${moduleName}`)}
                        </td>
                        {actions.map((action) => (
                          <td key={action} className="p-3 text-center">
                            <FormField
                              control={form.control as any}
                              name={
                                `permissions.${moduleName}.${action}` as any
                              }
                              render={({ field }) => (
                                <FormControl>
                                  <Checkbox
                                    checked={field.value}
                                    onCheckedChange={field.onChange}
                                  />
                                </FormControl>
                              )}
                            />
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
              >
                {t('admin.rolesManagement.form.cancel')}
              </Button>
              <Button type="submit">
                {t('admin.rolesManagement.form.submit')}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
