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

interface Playlist {
  id: number;
  name?: string;
  description?: string;
  image_id?: number | null;
  image?: unknown;
  detail_image_id?: number | null;
  detail_image?: unknown;
  is_premium?: boolean;
}

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

export default function MusicPlaylistsPage() {
  const { data, loading, error, reload } = useList<Playlist>("/music-playlists");
  const { data: categories } = useList<MusicCategory>("/music-categories");
  const { data: subcategories } = useList<MusicCategory>("/music-subcategories");
  const toast = useToast();

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

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [categoryIds, setCategoryIds] = useState<number[]>([]);
  const [subcategoryIds, setSubcategoryIds] = useState<number[]>([]);
  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 [isPremium, setIsPremium] = useState(false);

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

  function toggle(list: number[], id: number): number[] {
    return list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
  }

  function openCreate() {
    setEditing(null);
    setName("");
    setDescription("");
    setCategoryIds([]);
    setSubcategoryIds([]);
    setImageId(null);
    setImageFile(null);
    setDetailImageId(null);
    setDetailImageFile(null);
    setIsPremium(false);
    setOpen(true);
  }
  function openEdit(row: Playlist) {
    setEditing(row);
    setName(row.name ?? "");
    setDescription(row.description ?? "");
    setCategoryIds([]);
    setSubcategoryIds([]);
    setImageId(row.image_id ?? null);
    setImageFile(null);
    setDetailImageId(row.detail_image_id ?? null);
    setDetailImageFile(null);
    setIsPremium(row.is_premium ?? false);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      if (editing) {
        // Update is multipart (POST) so an image file can be uploaded.
        await apiFetch(`/music-playlists/${editing.id}`, {
          method: "POST",
          body: toFormData({
            name,
            description,
            image_id: imageId,
            image: imageFile,
            detail_image_id: detailImageId,
            detail_image: detailImageFile,
            is_premium: isPremium,
          }),
        });
        toast.success("پلی‌لیست ویرایش شد.");
      } else {
        // Create is multipart on /music-playlists
        await apiFetch("/music-playlists", {
          method: "POST",
          body: toFormData({
            name,
            description,
            category_ids: categoryIds,
            subcategory_ids: subcategoryIds,
            image_id: imageId,
            image: imageFile,
            detail_image_id: detailImageId,
            detail_image: detailImageFile,
            is_premium: isPremium,
          }),
        });
        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(`/music-playlists/${deleting.id}`, { method: "DELETE" });
      toast.success("پلی‌لیست حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<Playlist>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
    {
      key: "image",
      header: "تصویر",
      className: "w-20",
      render: (r) => (
        <MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.name} />
      ),
    },
    { key: "name", header: "نام" },
    {
      key: "description",
      header: "توضیحات",
      render: (r) => r.description ?? "—",
    },
    {
      key: "is_premium",
      header: "ویژه",
      className: "w-20",
      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>
        }
      />

      <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="playlist-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="playlist-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="توضیحات">
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="توضیح کوتاه درباره پلی‌لیست"
            />
          </Field>

          <Field label="تصویر لیست">
            <ImagePicker
              imageId={imageId}
              onPickId={setImageId}
              file={imageFile}
              onPickFile={setImageFile}
              existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
            />
          </Field>

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

          <Switch checked={isPremium} onChange={setIsPremium} label="ویژه (پرمیوم)" />

          {!editing && (
            <>
              <Field label="دسته‌بندی‌ها">
                <div className="flex flex-col gap-2 rounded-xl border border-border p-3">
                  {categories.length === 0 && (
                    <span className="text-xs text-muted">موردی موجود نیست</span>
                  )}
                  {categories.map((c) => (
                    <label
                      key={c.id}
                      className="flex items-center gap-2 text-sm"
                    >
                      <input
                        type="checkbox"
                        checked={categoryIds.includes(c.id)}
                        onChange={() =>
                          setCategoryIds((prev) => toggle(prev, c.id))
                        }
                      />
                      {c.name ?? `#${c.id}`}
                    </label>
                  ))}
                </div>
              </Field>

              <Field label="زیر‌دسته‌ها">
                <div className="flex flex-col gap-2 rounded-xl border border-border p-3">
                  {subcategories.length === 0 && (
                    <span className="text-xs text-muted">موردی موجود نیست</span>
                  )}
                  {subcategories.map((c) => (
                    <label
                      key={c.id}
                      className="flex items-center gap-2 text-sm"
                    >
                      <input
                        type="checkbox"
                        checked={subcategoryIds.includes(c.id)}
                        onChange={() =>
                          setSubcategoryIds((prev) => toggle(prev, c.id))
                        }
                      />
                      {c.name ?? `#${c.id}`}
                    </label>
                  ))}
                </div>
              </Field>
            </>
          )}
        </form>
      </Modal>

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