"use client";

import { useMemo, useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
  Badge,
  Button,
  ConfirmDialog,
  Field,
  Input,
  Textarea,
  Select,
  Modal,
  PageHeader,
  Switch,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";

interface Faq {
  id: number;
  faq_category_id?: number;
  question?: string;
  answer?: string;
  order?: number;
  is_active?: boolean;
  category_name?: string;
}

interface FaqCategory {
  id: number;
  name?: string;
  faqs?: Faq[];
}

export default function FaqsPage() {
  // /faqs returns categories each with their faqs; flatten for the table.
  const { data: grouped, loading, error, reload } = useList<FaqCategory>(
    "/faqs?include_inactive=1",
  );
  const { data: categories } = useList<FaqCategory>("/faq-categories?include_inactive=1");
  const toast = useToast();

  const rows = useMemo<Faq[]>(
    () =>
      grouped.flatMap((c) =>
        (c.faqs ?? []).map((f) => ({ ...f, category_name: c.name })),
      ),
    [grouped],
  );

  const [editing, setEditing] = useState<Faq | null>(null);
  const [open, setOpen] = useState(false);
  const [categoryId, setCategoryId] = useState("");
  const [question, setQuestion] = useState("");
  const [answer, setAnswer] = useState("");
  const [order, setOrder] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [saving, setSaving] = useState(false);

  const [deleting, setDeleting] = useState<Faq | null>(null);
  const [removing, setRemoving] = useState(false);

  function openCreate() {
    setEditing(null);
    setCategoryId(categories[0] ? String(categories[0].id) : "");
    setQuestion("");
    setAnswer("");
    setOrder("");
    setIsActive(true);
    setOpen(true);
  }
  function openEdit(row: Faq) {
    setEditing(row);
    setCategoryId(row.faq_category_id != null ? String(row.faq_category_id) : "");
    setQuestion(row.question ?? "");
    setAnswer(row.answer ?? "");
    setOrder(row.order != null ? String(row.order) : "");
    setIsActive(row.is_active ?? true);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!categoryId) {
      toast.error("دسته‌بندی را انتخاب کنید.");
      return;
    }
    setSaving(true);
    try {
      const body = {
        faq_category_id: Number(categoryId),
        question,
        answer,
        order: order === "" ? undefined : Number(order),
        is_active: isActive,
      };
      if (editing) {
        await apiFetch(`/faqs/${editing.id}`, { method: "PUT", body });
        toast.success("پرسش ویرایش شد.");
      } else {
        await apiFetch("/faqs", { method: "POST", body });
        toast.success("پرسش افزوده شد.");
      }
      setOpen(false);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
    } finally {
      setSaving(false);
    }
  }

  async function confirmDelete() {
    if (!deleting) return;
    setRemoving(true);
    try {
      await apiFetch(`/faqs/${deleting.id}`, { method: "DELETE" });
      toast.success("پرسش حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<Faq>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    { key: "category", header: "دسته‌بندی", render: (r) => r.category_name ?? "—" },
    { key: "question", header: "پرسش", render: (r) => r.question ?? "—" },
    {
      key: "answer",
      header: "پاسخ",
      render: (r) =>
        r.answer ? (
          <span className="line-clamp-1 max-w-md text-muted">{r.answer}</span>
        ) : (
          "—"
        ),
    },
    { key: "order", header: "ترتیب", render: (r) => toFa(r.order ?? 0), className: "w-20" },
    {
      key: "is_active",
      header: "وضعیت",
      className: "w-24",
      render: (r) =>
        r.is_active ? <Badge tone="success">فعال</Badge> : <Badge tone="neutral">غیرفعال</Badge>,
    },
  ];

  return (
    <div>
      <PageHeader
        title="سوالات متداول"
        subtitle="مدیریت پرسش‌ها و پاسخ‌های پرتکرار"
        action={
          <Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
            پرسش جدید
          </Button>
        }
      />

      <DataTable
        columns={columns}
        rows={rows}
        loading={loading}
        error={error}
        onRetry={reload}
        emptyMessage="هنوز پرسشی ثبت نشده است."
        emptyAction={
          <Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
            پرسش جدید
          </Button>
        }
        actions={(row) => (
          <>
            <Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
              <EditIcon className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              onClick={() => setDeleting(row)}
              aria-label="حذف"
              className="text-danger"
            >
              <TrashIcon className="h-4 w-4" />
            </Button>
          </>
        )}
      />

      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={editing ? "ویرایش پرسش" : "پرسش جدید"}
        footer={
          <>
            <Button variant="secondary" onClick={() => setOpen(false)}>
              انصراف
            </Button>
            <Button form="faq-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="faq-form" onSubmit={save} className="flex flex-col gap-4">
          <Field label="دسته‌بندی" required>
            <Select value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
              <option value="">— انتخاب دسته‌بندی —</option>
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name ?? `#${c.id}`}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="پرسش" required>
            <Input
              value={question}
              onChange={(e) => setQuestion(e.target.value)}
              placeholder="مثلاً چطور رمز عبورم را تغییر دهم؟"
              required
              autoFocus
            />
          </Field>
          <Field label="پاسخ" required>
            <Textarea
              value={answer}
              onChange={(e) => setAnswer(e.target.value)}
              placeholder="پاسخ کامل پرسش"
              required
            />
          </Field>
          <Field label="ترتیب">
            <Input
              type="number"
              value={order}
              onChange={(e) => setOrder(e.target.value)}
              dir="ltr"
            />
          </Field>
          <Switch checked={isActive} onChange={setIsActive} label="فعال" />
        </form>
      </Modal>

      <ConfirmDialog
        open={!!deleting}
        message={`آیا از حذف این پرسش مطمئن هستید؟`}
        loading={removing}
        onConfirm={confirmDelete}
        onClose={() => setDeleting(null)}
      />
    </div>
  );
}
