"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,
  Badge,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl, IMAGE_KEYS } from "@/lib/media";

interface ImageItem {
  id: number;
  title?: string;
  type?: string;
  description?: string;
  url?: string;
  image?: string;
  path?: string;
}

type ImageType = "public" | "private";

const typeLabels: Record<string, string> = {
  public: "عمومی",
  private: "خصوصی",
};

export default function ImagesPage() {
  const { data, loading, error, reload } = useList<ImageItem>("/images/all");
  const toast = useToast();

  const [editing, setEditing] = useState<ImageItem | null>(null);
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [type, setType] = useState<ImageType>("public");
  const [description, setDescription] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);

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

  function openCreate() {
    setEditing(null);
    setTitle("");
    setType("public");
    setDescription("");
    setFile(null);
    setOpen(true);
  }
  function openEdit(row: ImageItem) {
    setEditing(row);
    setTitle(row.title ?? "");
    setType(row.type === "private" ? "private" : "public");
    setDescription(row.description ?? "");
    setFile(null);
    setOpen(true);
  }

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

  const columns: Column<ImageItem>[] = [
    {
      key: "preview",
      header: "پیش‌نمایش",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.title} />
      ),
    },
    { key: "title", header: "عنوان", render: (r) => r.title ?? "—" },
    {
      key: "type",
      header: "نوع",
      render: (r) =>
        r.type ? (
          <Badge tone={r.type === "private" ? "danger" : "primary"}>
            {typeLabels[r.type] ?? r.type}
          </Badge>
        ) : (
          <span className="text-muted">—</span>
        ),
    },
    {
      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="image-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="image-form" onSubmit={save} className="flex flex-col gap-4">
          {!editing && (
            <Field label="فایل تصویر" required>
              <Input
                type="file"
                accept="image/*"
                onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                required
              />
            </Field>
          )}
          <Field label="عنوان">
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="مثلاً پس‌زمینه آرامش"
              autoFocus
            />
          </Field>
          <Field label="نوع">
            <Select
              value={type}
              onChange={(e) => setType(e.target.value as ImageType)}
            >
              <option value="public">عمومی</option>
              <option value="private">خصوصی</option>
            </Select>
          </Field>
          <Field label="توضیحات">
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="توضیح کوتاه درباره تصویر"
            />
          </Field>
        </form>
      </Modal>

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