"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { PageHeader } from "@/components/layout/PageHeader";
import { DataTable, DataTableEmpty } from "@/components/layout/DataTable";
import { ListExportActions } from "@/components/export/ListExportActions";
import { Button } from "@/components/ui/Button";
import { Field, Input } from "@/components/ui/Field";
import { apiGet, apiPost } from "@/lib/api";

interface RoleRow {
  id: number;
  name: string;
  label_fa: string;
  is_system: boolean;
  permissions: string[];
  permission_labels: string[];
}

export default function RolesPage() {
  const [roles, setRoles] = useState<RoleRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [form, setForm] = useState({ name: "", label_fa: "", description: "" });

  const load = async () => {
    setLoading(true);
    try {
      setRoles(await apiGet("/roles"));
    } finally {
      setLoading(false);
    }
  };

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

  const createRole = async () => {
    await apiPost("/roles", form);
    setShowCreate(false);
    setForm({ name: "", label_fa: "", description: "" });
    await load();
  };

  return (
    <AppShell title="نقش‌ها و دسترسی‌ها">
      <PageHeader
        title="فهرست نقش‌ها"
        actions={
          <>
            <ListExportActions
              exportPath="/roles/export"
              filters={{}}
              filenameBase="roles-export"
            />
            <Button onClick={() => setShowCreate(true)}>نقش جدید</Button>
          </>
        }
      />

      {showCreate ? (
        <div className="mb-4 rounded-2xl border bg-white p-4">
          <div className="grid gap-3 lg:grid-cols-3">
            <Field label="شناسه (slug)"><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="custom_role" /></Field>
            <Field label="عنوان فارسی"><Input value={form.label_fa} onChange={(e) => setForm({ ...form, label_fa: e.target.value })} /></Field>
            <Field label="توضیح"><Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></Field>
          </div>
          <div className="mt-3 flex gap-2">
            <Button onClick={createRole}>ثبت</Button>
            <Button variant="secondary" onClick={() => setShowCreate(false)}>انصراف</Button>
          </div>
        </div>
      ) : null}

      <DataTable
        loading={loading}
        columns={[{ key: "i", label: "#" }, { key: "title", label: "عنوان" }, { key: "perms", label: "دسترسی‌ها" }, { key: "ops", label: "عملیات" }]}
      >
        {roles.length === 0 ? (
          <DataTableEmpty colSpan={4} />
        ) : (
          roles.map((r, i) => (
            <tr key={r.id}>
              <td className="px-3 py-2">{i + 1}</td>
              <td className="px-3 py-2 font-medium">{r.label_fa}</td>
              <td className="px-3 py-2">
                <div className="flex flex-wrap gap-1">
                  {r.permission_labels.slice(0, 6).map((p) => (
                    <span key={p} className="rounded-full bg-teal-100 px-2 py-0.5 text-[10px] text-teal-800">{p}</span>
                  ))}
                  {r.permission_labels.length > 6 ? <span className="text-xs text-[var(--muted)]">+{r.permission_labels.length - 6}</span> : null}
                </div>
              </td>
              <td className="px-3 py-2">
                <Link href={`/roles/${r.id}`} className="text-xs text-primary">مدیریت دسترسی</Link>
              </td>
            </tr>
          ))
        )}
      </DataTable>
    </AppShell>
  );
}
