"use client";

import { useMemo, useState, useTransition } from "react";
import { PlusCircle, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { handleUpdateGeneralSettings } from "@/lib/actions";
import { EMPLOYEE_PERMISSION_DEFINITIONS, getEmployeePermissionProfilesFromSettings } from "@/lib/employee-permissions";
import { useToast } from "@/hooks/use-toast";

type EditableProfile = {
  id: string;
  name: string;
  description?: string;
  role: "admin" | "employee" | "pos";
  permissions: string[];
};

type PermissionsProfilesManagerProps = {
  currentSettings: Record<string, any>;
  tGlobal?: Record<string, any>;
  formId?: string;
};

function normalizeProfiles(profiles: EditableProfile[]): EditableProfile[] {
  return profiles
    .map((entry, index) => {
      const role = entry.role === "admin" || entry.role === "employee" || entry.role === "pos" ? entry.role : "employee";
      const allowedPermissions = new Set(
        EMPLOYEE_PERMISSION_DEFINITIONS
          .filter((definition) => definition.roles.includes(role))
          .map((definition) => definition.key)
      );

      return {
        id: String(entry.id || `permission-profile-${Date.now()}-${index}`),
        name: String(entry.name || "").trim(),
        description: String(entry.description || "").trim() || undefined,
        role,
        permissions: Array.from(
          new Set(
            (Array.isArray(entry.permissions) ? entry.permissions : [])
              .map((permission) => String(permission || "").trim())
              .filter((permission) => allowedPermissions.has(permission as any))
          )
        ),
      };
    })
    .filter((entry) => entry.name.length > 0);
}

export default function PermissionsProfilesManager({ currentSettings, tGlobal = {}, formId }: PermissionsProfilesManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [profiles, setProfiles] = useState<EditableProfile[]>(() =>
    getEmployeePermissionProfilesFromSettings(currentSettings).map((entry) => ({
      id: String(entry.id || `permission-profile-${Date.now()}`),
      name: String(entry.name || ""),
      description: String(entry.description || "").trim() || "",
      role: entry.role,
      permissions: Array.from(new Set((entry.permissions || []).map((permission) => String(permission || "")))),
    }))
  );
  const [selectedProfileId, setSelectedProfileId] = useState<string>(() => profiles[0]?.id || "");

  const selectedIndex = useMemo(() => profiles.findIndex((entry) => entry.id === selectedProfileId), [profiles, selectedProfileId]);
  const selectedProfile = selectedIndex >= 0 ? profiles[selectedIndex] : null;

  const availablePermissions = useMemo(() => {
    if (!selectedProfile) return [];
    return EMPLOYEE_PERMISSION_DEFINITIONS.filter((definition) => definition.roles.includes(selectedProfile.role));
  }, [selectedProfile]);

  const updateSelectedProfile = (updater: (current: EditableProfile) => EditableProfile) => {
    if (selectedIndex < 0) return;
    setProfiles((prev) => {
      const next = [...prev];
      next[selectedIndex] = updater(next[selectedIndex]);
      return next;
    });
  };

  const addProfile = () => {
    const newId = `permission-profile-${Date.now()}`;
    const nextProfile: EditableProfile = {
      id: newId,
      name: "",
      description: "",
      role: "employee",
      permissions: [],
    };
    setProfiles((prev) => [...prev, nextProfile]);
    setSelectedProfileId(newId);
  };

  const removeSelectedProfile = () => {
    if (!selectedProfile) return;
    setProfiles((prev) => {
      const next = prev.filter((entry) => entry.id !== selectedProfile.id);
      setSelectedProfileId(next[0]?.id || "");
      return next;
    });
  };

  const togglePermission = (permissionKey: string, checked: boolean) => {
    updateSelectedProfile((profile) => {
      const current = Array.isArray(profile.permissions) ? profile.permissions : [];
      const nextPermissions = checked
        ? Array.from(new Set([...current, permissionKey]))
        : current.filter((entry) => entry !== permissionKey);
      return { ...profile, permissions: nextPermissions };
    });
  };

  const handleSave = () => {
    startTransition(async () => {
      const normalizedProfiles = normalizeProfiles(profiles);
      const result = await handleUpdateGeneralSettings({
        ...currentSettings,
        employeePermissionProfiles: normalizedProfiles,
      } as any);

      if (result?.error) {
        toast({
          title: tGlobal?.error ?? "خطأ",
          description: result.error,
          variant: "destructive",
        });
        return;
      }

      setProfiles(normalizedProfiles);
      setSelectedProfileId((prev) => normalizedProfiles.find((entry) => entry.id === prev)?.id || normalizedProfiles[0]?.id || "");
      toast({
        title: tGlobal?.success ?? "تم",
        description: "تم حفظ أنواع الموظفين والصلاحيات بنجاح.",
      });
    });
  };

  return (
    <form
      id={formId}
      className="space-y-4 rounded-md border p-4"
      onSubmit={(event) => {
        event.preventDefault();
        handleSave();
      }}
    >
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 className="font-semibold">إدارة الصلاحيات</h3>
          <p className="text-sm text-muted-foreground">
            اختر نوع الموظف من القائمة، ثم عدل الوصف والصلاحيات واحفظ التغييرات.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button type="button" variant="outline" onClick={addProfile}>
            <PlusCircle className="me-2 h-4 w-4" />
            إضافة نوع جديد
          </Button>
          <Button type="button" variant="ghost" size="icon" onClick={removeSelectedProfile} disabled={!selectedProfile}>
            <Trash2 className="h-4 w-4 text-destructive" />
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <div className="space-y-2">
          <p className="text-sm font-medium">اختيار النوع</p>
          <Select value={selectedProfileId} onValueChange={setSelectedProfileId}>
            <SelectTrigger>
              <SelectValue placeholder="اختر نوع الموظف" />
            </SelectTrigger>
            <SelectContent>
              {profiles.map((profile, index) => (
                <SelectItem key={profile.id} value={profile.id}>
                  {profile.name || `نوع موظف ${index + 1}`}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {!selectedProfile && (
        <div className="rounded-md border border-dashed p-4 text-sm text-muted-foreground">
          لا توجد أنواع موظفين حالياً. أضف نوعاً جديداً للبدء.
        </div>
      )}

      {selectedProfile && (
        <div className="space-y-4 rounded-lg border p-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <p className="text-sm font-medium">اسم النوع</p>
              <Input
                value={selectedProfile.name || ""}
                placeholder="مثل: مسؤول مشتريات"
                onChange={(event) => updateSelectedProfile((profile) => ({ ...profile, name: event.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium">الدور الأساسي</p>
              <Select
                value={selectedProfile.role}
                onValueChange={(value) => {
                  const nextRole = value === "admin" || value === "employee" || value === "pos" ? value : "employee";
                  updateSelectedProfile((profile) => {
                    const allowedPermissions = new Set(
                      EMPLOYEE_PERMISSION_DEFINITIONS
                        .filter((definition) => definition.roles.includes(nextRole))
                        .map((definition) => definition.key)
                    );
                    return {
                      ...profile,
                      role: nextRole,
                      permissions: (profile.permissions || []).filter((permission) => allowedPermissions.has(permission as any)),
                    };
                  });
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="admin">مدير / إداري</SelectItem>
                  <SelectItem value="employee">موظف</SelectItem>
                  <SelectItem value="pos">POS</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-2">
            <p className="text-sm font-medium">وصف النوع</p>
            <Textarea
              value={selectedProfile.description || ""}
              rows={2}
              placeholder="وصف مختصر لاستخدام هذا النوع داخل النظام"
              onChange={(event) => updateSelectedProfile((profile) => ({ ...profile, description: event.target.value }))}
            />
          </div>

          <div className="space-y-3">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <p className="text-sm font-medium">
                الصلاحيات المتاحة{" "}
                <span className="font-normal text-muted-foreground">
                  ({(selectedProfile.permissions || []).filter((k) => availablePermissions.some((p) => p.key === k)).length} / {availablePermissions.length} مفعّلة)
                </span>
              </p>
              <div className="flex gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    updateSelectedProfile((profile) => ({
                      ...profile,
                      permissions: Array.from(new Set([...(profile.permissions || []), ...availablePermissions.map((p) => p.key)])),
                    }))
                  }
                >
                  تحديد الكل
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    updateSelectedProfile((profile) => ({
                      ...profile,
                      permissions: (profile.permissions || []).filter((k) => !availablePermissions.some((p) => p.key === k)),
                    }))
                  }
                >
                  إلغاء تحديد الكل
                </Button>
              </div>
            </div>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {availablePermissions.map((permission) => {
                const isChecked = (selectedProfile.permissions || []).includes(permission.key);
                return (
                  <label key={permission.key} className="flex cursor-pointer items-start gap-3 rounded-md border p-3 text-sm hover:bg-muted/40">
                    <Checkbox
                      checked={isChecked}
                      onCheckedChange={(checked) => togglePermission(permission.key, checked === true)}
                    />
                    <div className="space-y-1">
                      <p className="font-medium">{permission.label}</p>
                      <p className="text-xs text-muted-foreground">{permission.description}</p>
                    </div>
                  </label>
                );
              })}
            </div>
          </div>

        </div>
      )}

    </form>
  );
}
