"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Pencil, Plus, Shield, Trash2, Users } from "lucide-react";
import BusinessRoleFormModal from "@/components/businesses/BusinessRoleFormModal";
import Button from "@/components/ui/Button";
import ConfirmModal from "@/components/ui/ConfirmModal";
import { useBusinessPanelAccess } from "@/hooks/useBusinessPanelAccess";

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

interface BusinessRolePermissionEntry {
  businessPermission: BusinessPermission;
}

interface RoleRow {
  id: string;
  name: string;
  description: string | null;
  isSystem: boolean;
  businessId: string | null;
  permissions: BusinessRolePermissionEntry[];
  _count: {
    businessMembers: number;
    franchiseMembers: number;
    locationStaff: number;
  };
}

export default function BusinessPanelRoles() {
  const t = useTranslations("businessPanel");
  const tr = useTranslations("businessRoles");
  const tc = useTranslations("common");
  const { businessId, canManageRoles } = useBusinessPanelAccess();

  const [roles, setRoles] = useState<RoleRow[]>([]);
  const [businessPermissions, setBusinessPermissions] = useState<BusinessPermission[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<{ open: boolean; role: RoleRow | null }>({
    open: false,
    role: null,
  });
  const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
  const [deleting, setDeleting] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/business-panel");
      if (!res.ok) throw new Error("Failed");
      const json = await res.json();
      setRoles(json.roles ?? []);
      setBusinessPermissions(json.businessPermissions ?? []);
    } catch {
      setRoles([]);
      setBusinessPermissions([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  async function handleDelete(id: string) {
    if (!businessId) return;
    setDeleting(true);
    try {
      await fetch(`/api/businesses/${businessId}/roles/${id}`, { method: "DELETE" });
      setDeleteTarget(null);
      fetchData();
    } finally {
      setDeleting(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[var(--text)]">{t("rolesTitle")}</h2>
          <p className="mt-1 text-sm text-[var(--text-muted)]">{t("rolesSubtitle")}</p>
        </div>
        {canManageRoles && (
          <Button onClick={() => setModal({ open: true, role: null })} className="w-full sm:w-auto">
            <Plus className="h-4 w-4" />
            {tr("addRole")}
          </Button>
        )}
      </div>

      {loading ? (
        <p className="text-sm text-[var(--text-muted)]">{t("loading")}</p>
      ) : roles.length === 0 ? (
        <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center">
          <Shield className="mx-auto mb-2 h-8 w-8 text-[var(--text-faint)]" />
          <p className="text-sm text-[var(--text-muted)]">{t("noRoles")}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {roles.map((role) => {
            const memberTotal =
              (role._count.businessMembers ?? 0) +
              (role._count.franchiseMembers ?? 0) +
              (role._count.locationStaff ?? 0);
            const canEditRole = canManageRoles && !role.isSystem && role.businessId !== null;

            return (
              <div
                key={role.id}
                className="rounded-xl border border-[var(--border)] bg-[var(--bg)]/40 p-4"
              >
                <div className="flex flex-wrap items-start justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-sky-500/10 text-sky-400">
                      <Shield className="h-4 w-4" />
                    </div>
                    <div>
                      <div className="flex flex-wrap items-center gap-1.5">
                        <span className="font-medium text-[var(--text)]">{role.name}</span>
                        <span
                          className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                            role.isSystem
                              ? "bg-amber-500/10 text-amber-400"
                              : "bg-sky-500/10 text-sky-400"
                          }`}
                        >
                          {role.isSystem ? t("systemRole") : t("customRole")}
                        </span>
                      </div>
                      {role.description && (
                        <p className="mt-0.5 text-xs text-[var(--text-faint)]">{role.description}</p>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <div className="flex items-center gap-1 text-xs text-[var(--text-muted)]">
                      <Users className="h-3.5 w-3.5" />
                      {t("memberCount", { count: memberTotal })}
                    </div>
                    {canEditRole && (
                      <div className="flex items-center gap-1">
                        <button
                          type="button"
                          onClick={() => setModal({ open: true, role })}
                          className="cursor-pointer rounded-lg p-1.5 text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
                          aria-label={tc("edit")}
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </button>
                        <button
                          type="button"
                          onClick={() => setDeleteTarget({ id: role.id, name: role.name })}
                          className="cursor-pointer rounded-lg p-1.5 text-[var(--text-muted)] hover:bg-red-500/10 hover:text-red-500"
                          aria-label={tc("delete")}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    )}
                  </div>
                </div>

                <div className="mt-3">
                  {role.permissions.length === 0 ? (
                    <p className="text-xs text-[var(--text-faint)]">{t("noRolePermissions")}</p>
                  ) : (
                    <div className="flex flex-wrap gap-1.5">
                      {role.permissions.map((rp) => (
                        <span
                          key={rp.businessPermission.name}
                          className="rounded-full border border-[var(--border)] bg-[var(--bg-elevated)] px-2.5 py-1 text-[11px] text-[var(--text-muted)]"
                        >
                          {rp.businessPermission.name}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {modal.open && businessId && (
        <BusinessRoleFormModal
          businessId={businessId}
          role={modal.role}
          allPermissions={businessPermissions}
          onSave={() => {
            setModal({ open: false, role: null });
            fetchData();
          }}
          onClose={() => setModal({ open: false, role: null })}
        />
      )}

      <ConfirmModal
        open={Boolean(deleteTarget)}
        title={tc("confirmTitle")}
        description={
          deleteTarget ? `${tr("deleteConfirm")} (${deleteTarget.name})` : tc("confirmDelete")
        }
        loading={deleting}
        onConfirm={() => deleteTarget && handleDelete(deleteTarget.id)}
        onCancel={() => !deleting && setDeleteTarget(null)}
      />
    </div>
  );
}
