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

interface BellSound {
  id: number;
  name: string;
  order: number | null;
  is_active: boolean;
}

export default function BellSoundsPage() {
  const { data, loading, error, reload } = useList<BellSound>("/bell-sounds");
  const toast = useToast();

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

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

  function openCreate() {
    setEditing(null);
    setName("");
    setOrder("");
    setIsActive(true);
    setSound(null);
    setImage(null);
    setOpen(true);
  }
  function openEdit(row: BellSound) {
    setEditing(row);
    setName(row.name ?? "");
    setOrder(row.order?.toString() ?? "");
    setIsActive(!!row.is_active);
    setSound(null);
    setImage(null);
    setOpen(true);
  }

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

  const columns: Column<BellSound>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
    { key: "name", header: "نام" },
    {
      key: "preview",
      header: "پخش",
      render: (r) => (
        <MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.name} />
      ),
    },
    { key: "order", header: "ترتیب", render: (r) => toFa(r.order ?? "—") },
    {
      key: "is_active",
      header: "وضعیت",
      render: (r) =>
        r.is_active ? (
          <Badge tone="success">فعال</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="bell-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="bell-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"
              dir="ltr"
              value={order}
              onChange={(e) => setOrder(e.target.value)}
            />
          </Field>

          <Field label="وضعیت">
            <Switch
              checked={isActive}
              onChange={setIsActive}
              label={isActive ? "فعال" : "غیرفعال"}
            />
          </Field>

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

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

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