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

interface BreathingTemplate {
  id: number;
  name?: string;
  inhale?: number;
  exhale?: number;
  breath_hold?: number;
  duration?: number;
  description?: string;
  image_id?: number;
}

interface BreathingForm {
  name: string;
  inhale: string;
  exhale: string;
  breath_hold: string;
  duration: string;
  description: string;
  image_id: string;
}

const emptyForm: BreathingForm = {
  name: "",
  inhale: "",
  exhale: "",
  breath_hold: "",
  duration: "",
  description: "",
  image_id: "",
};

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

export default function BreathingPage() {
  const { data, loading, error, reload } =
    useList<BreathingTemplate>("/breathing-templates");
  const toast = useToast();

  const [editing, setEditing] = useState<BreathingTemplate | null>(null);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<BreathingForm>(emptyForm);
  const [saving, setSaving] = useState(false);

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

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

  function openCreate() {
    setEditing(null);
    setForm(emptyForm);
    setOpen(true);
  }
  function openEdit(row: BreathingTemplate) {
    setEditing(row);
    setForm({
      name: row.name ?? "",
      inhale: row.inhale != null ? String(row.inhale) : "",
      exhale: row.exhale != null ? String(row.exhale) : "",
      breath_hold: row.breath_hold != null ? String(row.breath_hold) : "",
      duration: row.duration != null ? String(row.duration) : "",
      description: row.description ?? "",
      image_id: row.image_id != null ? String(row.image_id) : "",
    });
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const payload = {
        name: form.name,
        inhale: numOrUndefined(form.inhale),
        exhale: numOrUndefined(form.exhale),
        breath_hold: numOrUndefined(form.breath_hold),
        duration: numOrUndefined(form.duration),
        description: form.description,
        image_id: numOrUndefined(form.image_id),
      };
      if (editing) {
        // Update is JSON on /breathing-templates/:id
        await apiFetch(`/breathing-templates/${editing.id}`, {
          method: "PUT",
          body: payload,
        });
        toast.success("قالب تنفس ویرایش شد.");
      } else {
        // Create is multipart on /breathing-templates
        await apiFetch("/breathing-templates", {
          method: "POST",
          body: toFormData(payload),
        });
        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(`/breathing-templates/${deleting.id}`, {
        method: "DELETE",
      });
      toast.success("قالب تنفس حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<BreathingTemplate>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    { key: "name", header: "نام", render: (r) => r.name ?? "—" },
    {
      key: "inhale",
      header: "دم",
      render: (r) => (r.inhale != null ? toFa(r.inhale) : "—"),
    },
    {
      key: "exhale",
      header: "بازدم",
      render: (r) => (r.exhale != null ? toFa(r.exhale) : "—"),
    },
    {
      key: "breath_hold",
      header: "حبس نفس",
      render: (r) => (r.breath_hold != null ? toFa(r.breath_hold) : "—"),
    },
    {
      key: "duration",
      header: "مدت زمان",
      render: (r) => (r.duration != null ? formatDuration(r.duration) : "—"),
    },
  ];

  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="breathing-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form
          id="breathing-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>
          <div className="grid grid-cols-2 gap-4">
            <Field label="دم (ثانیه)">
              <Input
                type="number"
                value={form.inhale}
                onChange={(e) => set("inhale", e.target.value)}
                dir="ltr"
              />
            </Field>
            <Field label="بازدم (ثانیه)">
              <Input
                type="number"
                value={form.exhale}
                onChange={(e) => set("exhale", e.target.value)}
                dir="ltr"
              />
            </Field>
            <Field label="حبس نفس (ثانیه)">
              <Input
                type="number"
                value={form.breath_hold}
                onChange={(e) => set("breath_hold", e.target.value)}
                dir="ltr"
              />
            </Field>
            <Field label="مدت زمان (ثانیه)">
              <Input
                type="number"
                value={form.duration}
                onChange={(e) => set("duration", e.target.value)}
                dir="ltr"
              />
            </Field>
          </div>
          <Field label="شناسه تصویر">
            <Input
              type="number"
              value={form.image_id}
              onChange={(e) => set("image_id", e.target.value)}
              dir="ltr"
            />
          </Field>
          <Field label="توضیحات">
            <Textarea
              value={form.description}
              onChange={(e) => set("description", e.target.value)}
              placeholder="توضیح کوتاه درباره قالب"
            />
          </Field>
        </form>
      </Modal>

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