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

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

interface Media {
  id: number;
  title?: string;
  caption?: string;
  // The API returns a `categories` array (many-to-many).
  categories?: Category[];
  subcategories?: Category[];
  subCategories?: Category[];
  type?: string;
  duration?: number;
  visibility?: string;
  is_premium?: boolean;
  external_url?: string | null;
  image_id?: number | null;
  image?: unknown;
  detail_image_id?: number | null;
  detail_image?: unknown;
}

// Compact multi-select rendered as toggle chips.
function ChipMultiSelect({
  options,
  selected,
  onToggle,
}: {
  options: Category[];
  selected: number[];
  onToggle: (id: number) => void;
}) {
  if (!options.length)
    return <p className="text-xs text-muted">موردی برای انتخاب نیست.</p>;
  return (
    <div className="flex flex-wrap gap-2">
      {options.map((o) => {
        const on = selected.includes(o.id);
        return (
          <button
            key={o.id}
            type="button"
            onClick={() => onToggle(o.id)}
            className={`rounded-full border px-3 py-1 text-xs transition ${
              on
                ? "border-primary bg-primary text-white"
                : "border-border bg-surface text-foreground hover:bg-surface-muted"
            }`}
          >
            {o.name ?? `#${o.id}`}
          </button>
        );
      })}
    </div>
  );
}

export default function MediaPage() {
  const [search, setSearch] = useState("");
  const { data, loading, error, reload } = useList<Media>("/media", { search });
  const { data: categories } = useList<Category>("/categories");
  const { data: subCategories } = useList<Category>("/sub-categories");
  const toast = useToast();

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

  const [title, setTitle] = useState("");
  const [caption, setCaption] = useState("");
  const [categoryIds, setCategoryIds] = useState<number[]>([]);
  const [subcategoryIds, setSubcategoryIds] = useState<number[]>([]);
  const [type, setType] = useState("audio");
  const [duration, setDuration] = useState("");
  const [visibility, setVisibility] = useState("public");
  const [isPremium, setIsPremium] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [externalUrl, setExternalUrl] = useState("");
  const [imageId, setImageId] = useState<number | null>(null);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [detailImageId, setDetailImageId] = useState<number | null>(null);
  const [detailImageFile, setDetailImageFile] = useState<File | null>(null);

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

  function resetForm() {
    setTitle("");
    setCaption("");
    setCategoryIds([]);
    setSubcategoryIds([]);
    setType("audio");
    setDuration("");
    setVisibility("public");
    setIsPremium(false);
    setFile(null);
    setExternalUrl("");
    setImageId(null);
    setImageFile(null);
    setDetailImageId(null);
    setDetailImageFile(null);
  }

  function openCreate() {
    setEditing(null);
    resetForm();
    setOpen(true);
  }

  function openEdit(row: Media) {
    setEditing(row);
    setTitle(row.title ?? "");
    setCaption(row.caption ?? "");
    setCategoryIds((row.categories ?? []).map((c) => c.id));
    setSubcategoryIds(
      (row.subcategories ?? row.subCategories ?? []).map((c) => c.id),
    );
    setType(row.type ?? "audio");
    setDuration(row.duration != null ? String(row.duration) : "");
    setVisibility(row.visibility ?? "public");
    setIsPremium(!!row.is_premium);
    setFile(null);
    setExternalUrl(row.external_url ?? "");
    setImageId(row.image_id ?? null);
    setImageFile(null);
    setDetailImageId(row.detail_image_id ?? null);
    setDetailImageFile(null);
    setOpen(true);
  }

  function toggleId(list: number[], set: (v: number[]) => void, id: number) {
    set(list.includes(id) ? list.filter((x) => x !== id) : [...list, id]);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const body = toFormData({
        title,
        caption,
        category_ids: categoryIds,
        subcategory_ids: subcategoryIds,
        type,
        duration,
        visibility,
        is_premium: isPremium,
        file,
        external_url: externalUrl,
        image_id: imageId,
        image: imageFile,
        detail_image_id: detailImageId,
        detail_image: detailImageFile,
      });
      if (editing) {
        // File-bearing update: POST /media/:id (multipart, file optional)
        await apiFetch(`/media/${editing.id}`, { method: "POST", body });
        toast.success("رسانه ویرایش شد.");
      } else {
        // Create: POST /media (multipart)
        await apiFetch("/media", { 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(`/media/${deleting.id}`, { method: "DELETE" });
      toast.success("رسانه حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<Media>[] = [
    {
      key: "play",
      header: "پخش",
      className: "w-20",
      render: (r) =>
        r.type === "video" ? (
          <MediaPreview kind="video" src={pickUrl(r, VIDEO_KEYS)} label={r.title} />
        ) : (
          <MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.title} />
        ),
    },
    {
      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: "categories",
      header: "دسته‌بندی",
      render: (r) =>
        r.categories?.length
          ? r.categories.map((c) => c.name).filter(Boolean).join("، ")
          : "—",
    },
    {
      key: "type",
      header: "نوع",
      render: (r) =>
        r.type === "video" ? "ویدیو" : r.type === "audio" ? "صوت" : (r.type ?? "—"),
    },
    {
      key: "duration",
      header: "مدت",
      render: (r) => formatMinutes(r.duration),
    },
    {
      key: "is_premium",
      header: "ویژه",
      render: (r) =>
        r.is_premium ? (
          <Badge tone="primary">ویژه</Badge>
        ) : (
          <Badge tone="neutral">رایگان</Badge>
        ),
    },
  ];

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

      <div className="mb-4 max-w-sm">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="جستجو در رسانه‌ها..."
        />
      </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="media-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="media-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="توضیحات">
            <Input
              value={caption}
              onChange={(e) => setCaption(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>

          <Field label="تصویر جزئیات" hint="در صفحه جزئیات نمایش داده می‌شود">
            <ImagePicker
              imageId={detailImageId}
              onPickId={setDetailImageId}
              file={detailImageFile}
              onPickFile={setDetailImageFile}
              existingUrl={editing ? pickUrl(editing, ["detail_image"]) : null}
            />
          </Field>

          <Field label="دسته‌بندی‌ها">
            <ChipMultiSelect
              options={categories}
              selected={categoryIds}
              onToggle={(id) => toggleId(categoryIds, setCategoryIds, id)}
            />
          </Field>

          <Field label="زیر‌دسته‌ها">
            <ChipMultiSelect
              options={subCategories}
              selected={subcategoryIds}
              onToggle={(id) => toggleId(subcategoryIds, setSubcategoryIds, id)}
            />
          </Field>

          <Field label="نوع" required>
            <Select value={type} onChange={(e) => setType(e.target.value)} required>
              <option value="audio">صوت</option>
              <option value="video">ویدیو</option>
            </Select>
          </Field>

          <Field
            label={editing ? "فایل (در صورت تغییر)" : "فایل"}
            hint="فایل صوتی/تصویری را بارگذاری کنید یا از «لینک خارجی» استفاده کنید."
          >
            <Input
              type="file"
              accept="audio/*,video/*"
              onChange={(e) => setFile(e.target.files?.[0] ?? null)}
            />
          </Field>

          <Field label="لینک خارجی" hint="اگر فایل آپلود نمی‌کنید، آدرس مستقیم فایل را وارد کنید.">
            <Input
              dir="ltr"
              value={externalUrl}
              onChange={(e) => setExternalUrl(e.target.value)}
              placeholder="https://..."
            />
          </Field>

          <Field label="مدت (دقیقه)">
            <Input
              type="number"
              dir="ltr"
              value={duration}
              onChange={(e) => setDuration(e.target.value)}
              placeholder="مثلاً ۱۰"
            />
          </Field>

          <Field label="دسترسی" required>
            <Select
              value={visibility}
              onChange={(e) => setVisibility(e.target.value)}
              required
            >
              <option value="public">عمومی</option>
              <option value="private">خصوصی</option>
            </Select>
          </Field>

          <Switch
            checked={isPremium}
            onChange={setIsPremium}
            label="محتوای ویژه (پولی)"
          />
        </form>
      </Modal>

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