'use client';

import { useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  addRole,
  fetchRoleById,
  updateRole,
} from '@/modules/Roles/apis/roles.apis';
import { assignPermissionsToRole } from '@/network/apis/dashboard/permissions/permissions.apis';
import { zodResolver } from '@hookform/resolvers/zod';
import { RiCheckboxCircleFill, RiErrorWarningFill, RiArrowLeftLine, RiSearchLine, RiShieldCheckLine } from '@remixicon/react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Alert, AlertIcon, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinners';
import { useLanguage } from '@/providers/i18n-provider';
import { RoleAddSchema, RoleAddSchemaType } from './role-add-schema';
import { usePermissions } from '../../hooks/usePermissions';

export default function CreateRole() {
  const router = useRouter();
  const params = useParams();
  const { languageCode } = useLanguage();
  const [permSearch, setPermSearch] = useState('');
  const [collapsedSections, setCollapsedSections] = useState<Set<string>>(new Set());

  const id = params?.slug?.[0] ? Number(params?.slug?.[0]) : undefined;
  const isEdit = !!id;

  const { data: roleDetails } = useQuery({
    queryKey: ['role_details', id],
    queryFn: async () => {
      if (!id) return;
      return await fetchRoleById(id.toString());
    },
    enabled: isEdit,
  });

  const form = useForm<RoleAddSchemaType>({
    resolver: zodResolver(RoleAddSchema),
    defaultValues: {
      name: '',
      name_ar: '',
      permissions: [],
    },
    mode: 'onSubmit',
  });

  const { data: permissions, isLoading } = usePermissions();

  useEffect(() => {
    if (isEdit && roleDetails) {
      const rolePermissions = roleDetails.permissions?.map((p) => p.name) || [];
      form.reset({
        name: roleDetails.name ?? '',
        name_ar: roleDetails.name_ar ?? '',
        permissions: rolePermissions,
      });
    }
  }, [isEdit, roleDetails, form]);

  const filteredPermissions = useMemo(() => {
    if (!permissions) return [];
    if (!permSearch.trim()) return permissions;
    const q = permSearch.toLowerCase();
    return permissions
      .map((section) => {
        const filtered = section.permissions.filter(
          (p) =>
            p.name.toLowerCase().includes(q) ||
            p.name_en.toLowerCase().includes(q) ||
            p.name_ar?.toLowerCase().includes(q),
        );
        if (filtered.length === 0) return null;
        return { ...section, permissions: filtered };
      })
      .filter(Boolean) as typeof permissions;
  }, [permissions, permSearch]);

  const mutation = useMutation({
    mutationFn: async (values: RoleAddSchemaType) => {
      const data = { name: values.name, name_ar: values.name_ar };
      if (isEdit) {
        await updateRole(data, id?.toString());
        if (id && values.permissions.length > 0) {
          await assignPermissionsToRole(id.toString(), values.permissions);
        }
      } else {
        const createdRole = await addRole(data);
        const roleId = Array.isArray(createdRole)
          ? createdRole[0]?.id
          : (createdRole as unknown as Record<string, unknown>)?.id;
        if (roleId && values.permissions.length > 0) {
          await assignPermissionsToRole(String(roleId), values.permissions);
        }
      }
    },
    onSuccess: () => {
      const message = isEdit
        ? 'Role and permissions updated successfully'
        : 'Role and permissions created successfully';
      toast.custom(
        () => (
          <Alert variant="mono" icon="success" close={false}>
            <AlertIcon>
              <RiCheckboxCircleFill />
            </AlertIcon>
            <AlertTitle>{message}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
      router.push('/roles');
    },
    onError: (error: unknown) => {
      const err = error as Record<string, unknown>;
      const resp = err?.response as Record<string, unknown> | undefined;
      const respData = resp?.data as Record<string, unknown> | undefined;
      const errorMessage =
        (respData?.message as string) ||
        (err?.message as string) ||
        'Failed to save role';
      toast.custom(
        () => (
          <Alert variant="mono" icon="destructive" close={false}>
            <AlertIcon>
              <RiErrorWarningFill />
            </AlertIcon>
            <AlertTitle>{errorMessage}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
    },
  });

  const isProcessing = mutation.status === 'pending';
  const selectedPermissions = form.watch('permissions');
  const hasNoPermissions = !selectedPermissions || selectedPermissions.length === 0;

  const handleSubmit = (values: RoleAddSchemaType) => {
    mutation.mutate(values);
  };

  const toggleSection = (sectionKey: string) => {
    setCollapsedSections((prev) => {
      const next = new Set(prev);
      if (next.has(sectionKey)) next.delete(sectionKey);
      else next.add(sectionKey);
      return next;
    });
  };

  const handleSelectAll = (sectionPerms: { name: string }[], checked: boolean) => {
    const current = form.getValues('permissions') || [];
    const names = sectionPerms.map((p) => p.name);
    if (checked) {
      const merged = Array.from(new Set([...current, ...names]));
      form.setValue('permissions', merged, { shouldValidate: true });
    } else {
      form.setValue(
        'permissions',
        current.filter((p) => !names.includes(p)),
        { shouldValidate: true },
      );
    }
  };

  const isSectionAllSelected = (sectionPerms: { name: string }[]) => {
    const current = selectedPermissions || [];
    return sectionPerms.every((p) => current.includes(p.name));
  };

  const isSectionPartial = (sectionPerms: { name: string }[]) => {
    const current = selectedPermissions || [];
    const selected = sectionPerms.filter((p) => current.includes(p.name));
    return selected.length > 0 && selected.length < sectionPerms.length;
  };

  const getSectionSelectedCount = (sectionPerms: { name: string }[]) => {
    const current = selectedPermissions || [];
    return sectionPerms.filter((p) => current.includes(p.name)).length;
  };

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => router.push('/roles')}
        >
          <RiArrowLeftLine className="size-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">
            {isEdit ? 'Edit Role' : 'Create Role'}
          </h1>
          <p className="text-muted-foreground text-sm">
            {isEdit
              ? 'Update role details and manage permission assignments'
              : 'Define a new role and assign permissions to it'}
          </p>
        </div>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Role Details</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Role Name (English)</FormLabel>
                      <FormControl>
                        <Input placeholder="e.g. Content Manager" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="name_ar"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Role Name (Arabic)</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="مثال: مدير المحتوى"
                          dir="rtl"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex-row items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <CardTitle className="text-base">Permissions</CardTitle>
                {selectedPermissions && selectedPermissions.length > 0 && (
                  <Badge variant="info" appearance="outline">
                    {selectedPermissions.length} selected
                  </Badge>
                )}
              </div>
              <div className="relative w-72">
                <RiSearchLine className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                <Input
                  placeholder="Search permissions..."
                  value={permSearch}
                  onChange={(e) => setPermSearch(e.target.value)}
                  className="pl-9"
                />
              </div>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="flex items-center justify-center py-12">
                  <Spinner className="animate-spin" />
                  <span className="ml-2 text-muted-foreground">Loading permissions...</span>
                </div>
              ) : !filteredPermissions || filteredPermissions.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  {permSearch
                    ? 'No permissions match your search'
                    : 'No permissions available'}
                </div>
              ) : (
                <FormField
                  control={form.control}
                  name="permissions"
                  render={() => (
                    <FormItem>
                      <div className="space-y-3">
                        {filteredPermissions.map((section) => {
                          const sectionKey =
                            languageCode === 'ar'
                              ? section.section.ar
                              : section.section.en;
                          const isCollapsed = collapsedSections.has(sectionKey);
                          const allSelected = isSectionAllSelected(section.permissions);
                          const partial = isSectionPartial(section.permissions);
                          const count = getSectionSelectedCount(section.permissions);

                          return (
                            <div
                              key={sectionKey}
                              className="border rounded-xl overflow-hidden"
                            >
                              <div
                                className="flex items-center justify-between px-4 py-3 bg-accent/40 cursor-pointer select-none"
                                onClick={() => toggleSection(sectionKey)}
                              >
                                <div className="flex items-center gap-3">
                                  <Checkbox
                                    checked={allSelected ? true : partial ? 'indeterminate' : false}
                                    onCheckedChange={(checked) => {
                                      handleSelectAll(
                                        section.permissions,
                                        !!checked,
                                      );
                                    }}
                                    onClick={(e) => e.stopPropagation()}
                                  />
                                  <div className="flex items-center gap-2">
                                    <RiShieldCheckLine className="size-4 text-muted-foreground" />
                                    <span className="font-medium text-sm">
                                      {sectionKey}
                                    </span>
                                  </div>
                                  <Badge
                                    variant={count > 0 ? 'success' : 'mono'}
                                    appearance="outline"
                                    className="text-xs"
                                  >
                                    {count}/{section.permissions.length}
                                  </Badge>
                                </div>
                                <svg
                                  className={`size-4 text-muted-foreground transition-transform ${isCollapsed ? '' : 'rotate-180'}`}
                                  fill="none"
                                  viewBox="0 0 24 24"
                                  stroke="currentColor"
                                >
                                  <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M19 9l-7 7-7-7"
                                  />
                                </svg>
                              </div>
                              {!isCollapsed && (
                                <div className="p-4">
                                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2.5">
                                    {section.permissions.map((permission) => (
                                      <FormField
                                        key={permission.id}
                                        control={form.control}
                                        name="permissions"
                                        render={({ field }) => (
                                          <FormItem className="flex items-center gap-2 space-y-0 p-2.5 rounded-lg border hover:bg-accent/30 transition-colors">
                                            <FormControl>
                                              <Checkbox
                                                checked={field.value?.includes(
                                                  permission.name,
                                                )}
                                                onCheckedChange={(checked) => {
                                                  const current =
                                                    field.value || [];
                                                  if (checked) {
                                                    field.onChange([
                                                      ...current,
                                                      permission.name,
                                                    ]);
                                                  } else {
                                                    field.onChange(
                                                      current.filter(
                                                        (p) =>
                                                          p !== permission.name,
                                                      ),
                                                    );
                                                  }
                                                }}
                                              />
                                            </FormControl>
                                            <FormLabel className="text-sm font-normal cursor-pointer leading-tight">
                                              {languageCode === 'ar'
                                                ? permission.name_ar
                                                : permission.name_en}
                                            </FormLabel>
                                          </FormItem>
                                        )}
                                      />
                                    ))}
                                  </div>
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
            </CardContent>
          </Card>

          <div className="flex items-center justify-between">
            <Button
              type="button"
              variant="outline"
              onClick={() => router.push('/roles')}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isProcessing || hasNoPermissions}>
              {isProcessing && <Spinner className="animate-spin mr-1.5" />}
              {isEdit ? 'Update Role' : 'Create Role'}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
