"use client";

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

interface Category {
  id: number;
  name?: string;
}

interface SubCategory {
  id: number;
  name?: string;
  description?: string | null;
  category_id?: number;
  category?: { id?: number; name?: string };
}

export default function SubCategoriesPage() {
  const { data, loading, error, reload } = useList<SubCategory>("/sub-categories");
  const { data: categories } = useList<Category>("/categories");
  const toast = useToast();

  const [editing, setEditing] = useState<SubCategory | null>(null);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [categoryId, setCategoryId] = useState("");

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

  function openCreate() {
    setEditing(null);
    setName("");
    setDescription("");
    setCategoryId("");
    setOpen(true);
  }

  function openEdit(row: SubCategory) {
    setEditing(row);
    setName(row.name ?? "");
    setDescription(row.description ?? "");
    setCategoryId(
      row.category_id != null
        ? String(row.category_id)
        : row.category?.id != null
          ? String(row.category.id)
          : "",
    );
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      if (editing) {
        // Update is JSON on /sub-categories/:id
        await apiFetch(`/sub-categories/${editing.id}`, {
          method: "PUT",
          body: { name, category_id: categoryId, description },
        });
        toast.success("زیر‌دسته ویرایش شد.");
      } else {
        // Create is multipart on /sub-categories
        await apiFetch("/sub-categories", {
          method: "POST",
          body: toFormData({ category_id: categoryId, name, description }),
        });
        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(`/sub-categories/${deleting.id}`, { method: "DELETE" });
      toast.success("زیر‌دسته حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<SubCategory>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
    { key: "name", header: "نام", render: (r) => r.name ?? "—" },
    {
      key: "category",
      header: "دسته‌بندی والد",
      render: (r) => r.category?.name ?? "—",
    },
    {
      key: "description",
      header: "توضیحات",
      render: (r) => r.description || "—",
    },
  ];

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

      <DataTable
        columns={columns}
        rows={data}
        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="sub-category-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form
          id="sub-category-form"
          onSubmit={save}
          className="flex flex-col gap-4"
        >
          <Field label="دسته‌بندی والد" required>
            <Select
              value={categoryId}
              onChange={(e) => setCategoryId(e.target.value)}
              required
            >
              <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={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="مثلاً تمرکز"
              required
              autoFocus
            />
          </Field>

          <Field label="توضیحات">
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="توضیح کوتاه درباره این زیر‌دسته"
            />
          </Field>
        </form>
      </Modal>

      <ConfirmDialog
        open={!!deleting}
        message={`آیا از حذف «${deleting?.name ?? ""}» مطمئن هستید؟`}
        loading={removing}
        onConfirm={confirmDelete}
        onClose={() => setDeleting(null)}
      />
    </div>
  );
}
