"use client";

import { useState, useMemo } from "react";
import { useTranslations } from "next-intl";
import { Loader2, Search } from "lucide-react";
import Button from "@/components/ui/Button";
import FormSection from "@/components/ui/FormSection";
import Input from "@/components/ui/Input";
import Modal from "@/components/ui/Modal";

interface BusinessPermission {
  id: string;
  name: string;
  module: string;
  action: string;
  description: string | null;
}

interface BusinessRole {
  id: string;
  name: string;
  description: string | null;
  isSystem: boolean;
  permissions: { businessPermission: BusinessPermission }[];
}

interface BusinessRoleFormModalProps {
  businessId: string;
  role: BusinessRole | null;
  allPermissions: BusinessPermission[];
  onSave: () => void;
  onClose: () => void;
}

export default function BusinessRoleFormModal({ businessId, role, allPermissions, onSave, onClose }: BusinessRoleFormModalProps) {
  const t = useTranslations("businessRoles");
  const tc = useTranslations("common");

  const isEdit = Boolean(role);
  const [name, setName] = useState(role?.name ?? "");
  const [description, setDescription] = useState(role?.description ?? "");
  const [selectedIds, setSelectedIds] = useState<Set<string>>(
    new Set(role?.permissions.map((rp) => rp.businessPermission.id) ?? [])
  );
  const [search, setSearch] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const grouped = useMemo(() => {
    const filtered = allPermissions.filter(
      (p) => !search || p.module.includes(search.toLowerCase()) || p.action.includes(search.toLowerCase()) || p.name.toLowerCase().includes(search.toLowerCase())
    );
    const map: Record<string, BusinessPermission[]> = {};
    for (const p of filtered) {
      (map[p.module] ??= []).push(p);
    }
    return map;
  }, [allPermissions, search]);

  const togglePerm = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const toggleModule = (perms: BusinessPermission[]) => {
    const allSelected = perms.every((p) => selectedIds.has(p.id));
    setSelectedIds((prev) => {
      const next = new Set(prev);
      perms.forEach((p) => (allSelected ? next.delete(p.id) : next.add(p.id)));
      return next;
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const url = isEdit
        ? `/api/businesses/${businessId}/roles/${role!.id}`
        : `/api/businesses/${businessId}/roles`;
      const method = isEdit ? "PATCH" : "POST";
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, description: description || undefined, permissionIds: Array.from(selectedIds) }),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error ?? tc("somethingWrong"));
        return;
      }
      onSave();
    } catch {
      setError(tc("somethingWrong"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      wide
      title={isEdit ? t("editRole") : t("addRole")}
      description={t("formHint")}
      onClose={onClose}
    >
      <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
        <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-5 sm:px-6">
          <FormSection title={t("detailsSection")} hint={t("detailsHint")}>
            <Input
              label={t("roleName")}
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t("roleNamePlaceholder")}
              required
              disabled={isEdit && role?.isSystem}
            />
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={2}
              placeholder={t("descriptionPlaceholder")}
              className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] px-3 py-2.5 text-sm text-[var(--text)] placeholder:text-[var(--text-faint)] focus:border-[var(--accent)]/60 focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/40"
            />
          </FormSection>

          <FormSection title={t("permissions")}>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <p className="text-xs text-[var(--text-faint)]">{t("permissionsHint")}</p>
              <span className="rounded-md border border-[var(--border)] bg-[var(--bg-elevated)] px-2 py-1 text-[11px] text-[var(--text-faint)]">
                {selectedIds.size} {t("selected")}
              </span>
            </div>
            <div className="relative">
              <Search className="pointer-events-none absolute start-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--text-faint)]" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder={t("searchPermissions")}
                className="w-full rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] py-2 pe-3 ps-9 text-sm text-[var(--text)] placeholder:text-[var(--text-faint)] focus:border-[var(--accent)]/60 focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/40"
              />
            </div>
            <div className="max-h-56 space-y-3 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--bg-elevated)] p-3">
              {Object.entries(grouped).length === 0 ? (
                <p className="py-6 text-center text-xs text-[var(--text-muted)]">{t("noPermissions")}</p>
              ) : (
                Object.entries(grouped).map(([module, perms]) => {
                  const allSel = perms.every((p) => selectedIds.has(p.id));
                  return (
                    <div key={module}>
                      <button
                        type="button"
                        onClick={() => toggleModule(perms)}
                        className="mb-1.5 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] hover:text-[var(--text)]"
                      >
                        <div className={`h-3.5 w-3.5 rounded border transition-colors ${allSel ? "border-[var(--accent)] bg-[var(--accent)]" : "border-[var(--border)]"}`}>
                          {allSel && <svg viewBox="0 0 10 10" className="h-full w-full text-white"><path d="M2 5l2.5 2.5L8 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>}
                        </div>
                        {module}
                      </button>
                      <div className="flex flex-wrap gap-2">
                        {perms.map((p) => (
                          <button
                            key={p.id}
                            type="button"
                            onClick={() => togglePerm(p.id)}
                            title={p.description ?? ""}
                            className={`rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${
                              selectedIds.has(p.id)
                                ? "bg-[var(--accent)] text-white"
                                : "bg-[var(--bg)] text-[var(--text-muted)] ring-1 ring-[var(--border)] hover:ring-[var(--accent)]"
                            }`}
                          >
                            {p.action}
                          </button>
                        ))}
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </FormSection>

          {error && <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-500">{error}</p>}
        </div>

        <div className="flex shrink-0 items-center justify-end gap-2.5 border-t border-[var(--border)] bg-[var(--bg)]/40 px-5 py-4 sm:px-6">
          <Button type="button" variant="secondary" onClick={onClose} disabled={saving} className="min-w-[96px]">
            {tc("cancel")}
          </Button>
          <Button type="submit" disabled={saving || !name.trim() || (isEdit && role?.isSystem)} className="min-w-[110px]">
            {saving ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                {tc("saving")}
              </>
            ) : isEdit ? (
              tc("update")
            ) : (
              tc("create")
            )}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
