"use client";

import { useState } from "react";
import { apiFetch, ApiError } 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,
  Modal,
  PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa, formatDuration } from "@/lib/utils";

interface TimerPreset {
  id: number;
  name: string;
  duration_seconds: number;
  start_bell_id: number | null;
  end_bell_id: number | null;
  interval_bell_id: number | null;
  interval_seconds: number | null;
  interval_repeat: number | null;
  background_sound_id: number | null;
  background_image_id: number | null;
  volume: number | null;
}

interface BellSound {
  id: number;
  name: string;
}

interface BackgroundSound {
  id: number;
  name: string;
}

const emptyForm = {
  name: "",
  duration_seconds: "",
  start_bell_id: "",
  end_bell_id: "",
  interval_bell_id: "",
  interval_seconds: "",
  interval_repeat: "",
  background_sound_id: "",
  background_image_id: "",
  volume: "",
};

export default function TimerPresetsPage() {
  const { data, loading, error, reload } = useList<TimerPreset>("/timer-presets");
  const { data: bells } = useList<BellSound>("/bell-sounds");
  const { data: backgroundSounds } =
    useList<BackgroundSound>("/background-sounds");
  const toast = useToast();

  const [editing, setEditing] = useState<TimerPreset | null>(null);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ ...emptyForm });
  const [saving, setSaving] = useState(false);

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

  function set<K extends keyof typeof form>(key: K, value: string) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  function openCreate() {
    setEditing(null);
    setForm({ ...emptyForm });
    setOpen(true);
  }
  function openEdit(row: TimerPreset) {
    setEditing(row);
    setForm({
      name: row.name ?? "",
      duration_seconds: row.duration_seconds?.toString() ?? "",
      start_bell_id: row.start_bell_id?.toString() ?? "",
      end_bell_id: row.end_bell_id?.toString() ?? "",
      interval_bell_id: row.interval_bell_id?.toString() ?? "",
      interval_seconds: row.interval_seconds?.toString() ?? "",
      interval_repeat: row.interval_repeat?.toString() ?? "",
      background_sound_id: row.background_sound_id?.toString() ?? "",
      background_image_id: row.background_image_id?.toString() ?? "",
      volume: row.volume?.toString() ?? "",
    });
    setOpen(true);
  }

  function toNum(value: string): number | null {
    if (value === "" || value === null || value === undefined) return null;
    const n = Number(value);
    return Number.isNaN(n) ? null : n;
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const body = {
        name: form.name,
        duration_seconds: toNum(form.duration_seconds),
        start_bell_id: toNum(form.start_bell_id),
        end_bell_id: toNum(form.end_bell_id),
        interval_bell_id: toNum(form.interval_bell_id),
        interval_seconds: toNum(form.interval_seconds),
        interval_repeat: toNum(form.interval_repeat),
        background_sound_id: toNum(form.background_sound_id),
        background_image_id: toNum(form.background_image_id),
        volume: toNum(form.volume),
      };
      if (editing) {
        await apiFetch(`/timer-presets/${editing.id}`, {
          method: "PUT",
          body,
        });
        toast.success("پیش‌تنظیم ویرایش شد.");
      } else {
        await apiFetch("/timer-presets", {
          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(`/timer-presets/${deleting.id}`, { method: "DELETE" });
      toast.success("پیش‌تنظیم حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<TimerPreset>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-24" },
    { key: "name", header: "نام" },
    {
      key: "duration_seconds",
      header: "مدت",
      render: (r) => formatDuration(r.duration_seconds),
    },
    { key: "volume", header: "صدا", render: (r) => toFa(r.volume ?? "—") },
  ];

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

          <Field label="مدت (ثانیه)" required>
            <Input
              type="number"
              dir="ltr"
              value={form.duration_seconds}
              onChange={(e) => set("duration_seconds", e.target.value)}
              placeholder="مثلاً ۶۰۰"
              required
            />
          </Field>

          <Field label="زنگ شروع">
            <Select
              value={form.start_bell_id}
              onChange={(e) => set("start_bell_id", e.target.value)}
            >
              <option value="">— انتخاب کنید —</option>
              {bells.map((b) => (
                <option key={b.id} value={b.id}>
                  {b.name}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="زنگ پایان">
            <Select
              value={form.end_bell_id}
              onChange={(e) => set("end_bell_id", e.target.value)}
            >
              <option value="">— انتخاب کنید —</option>
              {bells.map((b) => (
                <option key={b.id} value={b.id}>
                  {b.name}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="زنگ میان‌دوره‌ای">
            <Select
              value={form.interval_bell_id}
              onChange={(e) => set("interval_bell_id", e.target.value)}
            >
              <option value="">— انتخاب کنید —</option>
              {bells.map((b) => (
                <option key={b.id} value={b.id}>
                  {b.name}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="فاصله زمانی (ثانیه)">
            <Input
              type="number"
              dir="ltr"
              value={form.interval_seconds}
              onChange={(e) => set("interval_seconds", e.target.value)}
            />
          </Field>

          <Field label="تعداد تکرار فاصله">
            <Input
              type="number"
              dir="ltr"
              value={form.interval_repeat}
              onChange={(e) => set("interval_repeat", e.target.value)}
            />
          </Field>

          <Field label="صدای پس‌زمینه">
            <Select
              value={form.background_sound_id}
              onChange={(e) => set("background_sound_id", e.target.value)}
            >
              <option value="">— انتخاب کنید —</option>
              {backgroundSounds.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
            </Select>
          </Field>

          <Field label="شناسه تصویر پس‌زمینه">
            <Input
              type="number"
              dir="ltr"
              value={form.background_image_id}
              onChange={(e) => set("background_image_id", e.target.value)}
            />
          </Field>

          <Field label="میزان صدا">
            <Input
              type="number"
              dir="ltr"
              value={form.volume}
              onChange={(e) => set("volume", e.target.value)}
              placeholder="مثلاً ۸۰"
            />
          </Field>
        </form>
      </Modal>

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