"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,
  Select,
  Textarea,
  Modal,
  PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl } from "@/lib/media";
import { toFa } from "@/lib/utils";

type CategoryType = "media" | "playlist" | "breathing_template";

interface Category {
  id: number;
  name: string;
  type: CategoryType;
  order?: number;
  description?: string | null;
  icon?: string | null;
  subcategories_count?: number;
}

// General category types, shared across media, playlists and breathing templates.
const TYPE_OPTIONS: { value: CategoryType; label: string }[] = [
  { value: "media", label: "رسانه" },
  { value: "playlist", label: "پلی‌لیست" },
  { value: "breathing_template", label: "قالب تنفس" },
];

const TYPE_LABELS: Record<CategoryType, string> = Object.fromEntries(
  TYPE_OPTIONS.map((o) => [o.value, o.label]),
) as Record<CategoryType, string>;

// The icon is a direct image-file field on the category (not an image_id ref).
const ICON_KEYS = ["icon", "icon_url"];

export default function CategoriesPage() {
  const [typeFilter, setTypeFilter] = useState<CategoryType>("media");
  const { data, loading, error, reload } = useList<Category>("/categories", {
    type: typeFilter,
  });
  const toast = useToast();

  const [editing, setEditing] = useState<Category | null>(null);
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [type, setType] = useState<CategoryType>("media");
  const [order, setOrder] = useState("0");
  const [description, setDescription] = useState("");
  const [icon, setIcon] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);

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

  function openCreate() {
    setEditing(null);
    setName("");
    setType(typeFilter);
    setOrder("0");
    setDescription("");
    setIcon(null);
    setOpen(true);
  }
  function openEdit(row: Category) {
    setEditing(row);
    setName(row.name ?? "");
    setType(row.type ?? "media");
    setOrder(String(row.order ?? 0));
    setDescription(row.description ?? "");
    setIcon(null);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      // Playlist categories live in the music_categories table, so their writes
      // go to /music-categories (image is the `image` field, not `icon`).
      const targetType = editing ? editing.type : type;
      if (targetType === "playlist") {
        const body = toFormData({ name, description, order, image: icon });
        if (editing) {
          await apiFetch(`/music-categories/${editing.id}`, { method: "POST", body });
          toast.success("دسته‌بندی ویرایش شد.");
        } else {
          await apiFetch("/music-categories", { method: "POST", body });
          toast.success("دسته‌بندی افزوده شد.");
        }
      } else if (editing) {
        // Icon is a file, so update goes through POST + Laravel method spoofing.
        const body = toFormData({
          _method: "PUT",
          name,
          type,
          order,
          description,
          icon,
        });
        await apiFetch(`/categories/${editing.id}`, { method: "POST", body });
        toast.success("دسته‌بندی ویرایش شد.");
      } else {
        await apiFetch("/categories", {
          method: "POST",
          body: toFormData({ name, type, order, description, icon }),
        });
        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 {
      const path =
        deleting.type === "playlist"
          ? `/music-categories/${deleting.id}`
          : `/categories/${deleting.id}`;
      await apiFetch(path, { method: "DELETE" });
      toast.success("دسته‌بندی حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<Category>[] = [
    {
      key: "icon",
      header: "آیکن",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="image" src={pickUrl(r, ICON_KEYS)} label={r.name} />
      ),
    },
    {
      key: "order",
      header: "ترتیب",
      render: (r) => toFa(r.order ?? 0),
      className: "w-20",
    },
    { key: "name", header: "نام دسته‌بندی" },
    {
      key: "type",
      header: "نوع",
      render: (r) => TYPE_LABELS[r.type] ?? r.type,
      className: "w-28",
    },
    {
      key: "description",
      header: "توضیحات",
      render: (r) => r.description || "—",
    },
    {
      key: "subcategories_count",
      header: "زیر‌دسته‌ها",
      render: (r) => toFa(r.subcategories_count ?? 0),
      className: "w-28",
    },
  ];

  return (
    <div>
      <PageHeader
        title="دسته‌بندی‌ها"
        subtitle="مدیریت دسته‌بندی‌های عمومی رسانه، پلی‌لیست و قالب تنفس"
        action={
          <div className="flex items-center gap-3">
            <Select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value as CategoryType)}
              aria-label="نوع دسته‌بندی"
              className="w-40"
            >
              {TYPE_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </Select>
            <Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
              دسته‌بندی جدید
            </Button>
          </div>
        }
      />

      <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="category-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="category-form" onSubmit={save} className="flex flex-col gap-4">
          <Field label="نوع" required>
            <Select
              value={type}
              onChange={(e) => setType(e.target.value as CategoryType)}
            >
              {TYPE_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="نام دسته‌بندی" required>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="مثلاً کودکان"
              required
              autoFocus
            />
          </Field>

          <Field label="ترتیب" hint="عدد کوچک‌تر بالاتر نمایش داده می‌شود.">
            <Input
              type="number"
              value={order}
              onChange={(e) => setOrder(e.target.value)}
              dir="ltr"
            />
          </Field>

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

          <Field
            label="آیکن"
            hint={
              editing
                ? "در صورت عدم انتخاب، آیکن فعلی حفظ می‌شود."
                : "یک تصویر برای نمایش دسته‌بندی انتخاب کنید."
            }
          >
            <Input
              type="file"
              accept="image/*"
              onChange={(e) => setIcon(e.target.files?.[0] ?? null)}
            />
          </Field>
        </form>
      </Modal>

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