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

interface Theme {
  id: number;
  key: string;
  name: string;
  colors: Record<string, string>;
}

interface Scene {
  id: number;
  name: string;
  order?: number;
  is_active?: boolean;
  theme_id?: number | null;
  theme?: Theme | null;
}

// "#FF156395" (ARGB) or "#156395" → a CSS color the browser understands.
function cssColor(c?: string): string {
  if (!c) return "transparent";
  const hex = c.replace("#", "");
  if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`; // ARGB → RGBA
  return `#${hex}`;
}

function ThemeSwatch({ theme }: { theme?: Theme | null }) {
  if (!theme) return <span className="text-muted">—</span>;
  const keys = ["themeUp", "themeDown", "lightColorGradient", "darkColorGradient"];
  return (
    <span className="inline-flex items-center gap-2">
      <span className="inline-flex overflow-hidden rounded-full border border-border">
        {keys.map((k) => (
          <span
            key={k}
            className="h-4 w-4"
            style={{ backgroundColor: cssColor(theme.colors?.[k]) }}
          />
        ))}
      </span>
      {theme.name}
    </span>
  );
}

export default function ScenesPage() {
  const { data, loading, error, reload } = useList<Scene>("/scenes");
  const { data: themes } = useList<Theme>("/themes");
  const toast = useToast();

  const [editing, setEditing] = useState<Scene | null>(null);
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [order, setOrder] = useState("");
  const [themeId, setThemeId] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [image, setImage] = useState<File | null>(null);
  const [video, setVideo] = useState<File | null>(null);
  const [sound, setSound] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);

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

  function openCreate() {
    setEditing(null);
    setName("");
    setOrder("");
    setThemeId("");
    setIsActive(true);
    setImage(null);
    setVideo(null);
    setSound(null);
    setOpen(true);
  }
  function openEdit(row: Scene) {
    setEditing(row);
    setName(row.name ?? "");
    setOrder(row.order != null ? String(row.order) : "");
    setThemeId(row.theme_id != null ? String(row.theme_id) : "");
    setIsActive(!!row.is_active);
    setImage(null);
    setVideo(null);
    setSound(null);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      // Scenes are file-bearing: both create and update use multipart POST.
      const body = toFormData({
        name,
        order,
        theme_id: themeId,
        is_active: isActive,
        image,
        video,
        sound,
      });
      if (editing) {
        await apiFetch(`/scenes/${editing.id}`, { method: "POST", body });
        toast.success("صحنه ویرایش شد.");
      } else {
        await apiFetch("/scenes", { 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(`/scenes/${deleting.id}`, { method: "DELETE" });
      toast.success("صحنه حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<Scene>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
    { key: "name", header: "نام صحنه" },
    {
      key: "theme",
      header: "قالب رنگی",
      render: (r) => <ThemeSwatch theme={r.theme} />,
    },
    {
      key: "image",
      header: "تصویر",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.name} />
      ),
    },
    {
      key: "video",
      header: "ویدیو",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="video" src={pickUrl(r, VIDEO_KEYS)} label={r.name} />
      ),
    },
    {
      key: "sound",
      header: "صدا",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.name} />
      ),
    },
    {
      key: "order",
      header: "ترتیب",
      render: (r) => (r.order != null ? toFa(r.order) : "—"),
      className: "w-24",
    },
    {
      key: "is_active",
      header: "وضعیت",
      render: (r) =>
        r.is_active ? (
          <Badge tone="success">فعال</Badge>
        ) : (
          <Badge tone="neutral">غیرفعال</Badge>
        ),
      className: "w-28",
    },
  ];

  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="scene-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="scene-form" onSubmit={save} className="flex flex-col gap-4">
          <Field label="نام صحنه" required>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="مثلاً جنگل بارانی"
              required
              autoFocus
            />
          </Field>

          <Field label="ترتیب">
            <Input
              type="number"
              value={order}
              onChange={(e) => setOrder(e.target.value)}
              placeholder="0"
              dir="ltr"
            />
          </Field>

          <Field label="قالب رنگی">
            <Select value={themeId} onChange={(e) => setThemeId(e.target.value)}>
              <option value="">— بدون قالب —</option>
              {themes.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.name}
                </option>
              ))}
            </Select>
            {themeId && (
              <div className="mt-2">
                <ThemeSwatch
                  theme={themes.find((t) => String(t.id) === themeId) ?? null}
                />
              </div>
            )}
          </Field>

          <Switch checked={isActive} onChange={setIsActive} label="فعال" />

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

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

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

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