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

interface AppVersion {
  id: number;
  title?: string;
  description?: string;
  version_name?: string;
  version_code?: number;
  link?: string;
  image_id?: number | null;
  image?: unknown;
}

export default function VersionsPage() {
  const { data, loading, error, reload } = useList<AppVersion>("/versions");
  const toast = useToast();

  const [editing, setEditing] = useState<AppVersion | null>(null);
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [versionName, setVersionName] = useState("");
  const [versionCode, setVersionCode] = useState("");
  const [link, setLink] = useState("");
  const [imageId, setImageId] = useState<number | null>(null);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);

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

  function openCreate() {
    setEditing(null);
    setTitle("");
    setDescription("");
    setVersionName("");
    setVersionCode("");
    setLink("");
    setImageId(null);
    setImageFile(null);
    setOpen(true);
  }
  function openEdit(row: AppVersion) {
    setEditing(row);
    setTitle(row.title ?? "");
    setDescription(row.description ?? "");
    setVersionName(row.version_name ?? "");
    setVersionCode(row.version_code != null ? String(row.version_code) : "");
    setLink(row.link ?? "");
    setImageId(row.image_id ?? null);
    setImageFile(null);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      // Multipart (the image is a file). Edit posts to /versions/:id, which the
      // backend also accepts as a multipart update.
      const body = toFormData({
        title,
        description,
        version_name: versionName,
        version_code: versionCode,
        link,
        image_id: imageId,
        image: imageFile,
      });
      if (editing) {
        await apiFetch(`/versions/${editing.id}`, { method: "POST", body });
        toast.success("نسخه ویرایش شد.");
      } else {
        await apiFetch("/versions", { 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(`/versions/${deleting.id}`, { method: "DELETE" });
      toast.success("نسخه حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<AppVersion>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    {
      key: "thumbnail",
      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: "version_name",
      header: "نام نسخه",
      render: (r) => (
        <span dir="ltr" className="block">
          {r.version_name ?? "—"}
        </span>
      ),
      className: "w-28",
    },
    {
      key: "version_code",
      header: "کد نسخه",
      render: (r) => (r.version_code != null ? toFa(r.version_code) : "—"),
      className: "w-24",
    },
    {
      key: "link",
      header: "لینک",
      render: (r) =>
        r.link ? (
          <span dir="ltr" className="block max-w-[12rem] truncate">
            {r.link}
          </span>
        ) : (
          "—"
        ),
    },
  ];

  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="version-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="version-form" onSubmit={save} className="flex flex-col gap-4">
          <Field label="عنوان" required>
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="مثلاً نسخه ۱.۲.۰"
              required
              autoFocus
            />
          </Field>

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

          <Field label="تصویر" hint="انتخاب از کتابخانه یا بارگذاری تصویر جدید">
            <ImagePicker
              imageId={imageId}
              onPickId={setImageId}
              file={imageFile}
              onPickFile={setImageFile}
              existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
            />
          </Field>

          <div className="grid grid-cols-2 gap-4">
            <Field label="نام نسخه" required>
              <Input
                value={versionName}
                onChange={(e) => setVersionName(e.target.value)}
                placeholder="1.2.0"
                dir="ltr"
                required
              />
            </Field>
            <Field label="کد نسخه" required>
              <Input
                type="number"
                value={versionCode}
                onChange={(e) => setVersionCode(e.target.value)}
                placeholder="42"
                dir="ltr"
                required
              />
            </Field>
          </div>

          <Field label="لینک">
            <Input
              value={link}
              onChange={(e) => setLink(e.target.value)}
              placeholder="https://"
              dir="ltr"
            />
          </Field>
        </form>
      </Modal>

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