import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { Bell, Trash2, ArrowLeft, Plus } from "lucide-react";
import { prisma } from "@/lib/db";
import { currentUser } from "@/lib/charts";
import { createReminderAction, deleteReminderAction } from "./_actions";
import { DateInput } from "@/components/ui/date-input";

export const metadata: Metadata = {
  title: "Nhắc nhở — Tử Vi Số",
};

export const dynamic = "force-dynamic";

const RECURRENCE_LABEL: Record<string, string> = {
  yearly: "Hằng năm",
  monthly: "Hằng tháng",
};

function formatDate(d: Date, isLunar: boolean): string {
  const s = d.toLocaleDateString("vi-VN", {
    weekday: "long",
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
  return isLunar ? `${s} (lịch âm)` : s;
}

export default async function RemindersPage() {
  const user = await currentUser();
  if (!user) redirect("/login?from=%2Fme%2Freminders");

  const reminders = await prisma.reminder.findMany({
    where: { userId: user.id },
    orderBy: { reminderDate: "asc" },
  });

  // Min date for the form = today (vi-VN local) so users don't pick the past.
  const today = new Date();
  const todayISO = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

  return (
    <div className="mx-auto max-w-3xl px-4 py-12">
      <div className="mb-6 flex items-center justify-between">
        <Link
          href="/me"
          className="inline-flex items-center gap-1.5 text-sm text-stone-400 hover:text-amber-500"
        >
          <ArrowLeft className="h-4 w-4" />
          Quay lại
        </Link>
      </div>

      <h1 className="font-serif text-3xl font-semibold text-stone-100">
        <Bell className="mr-2 inline-block h-7 w-7 text-amber-500" />
        Nhắc nhở của tôi
      </h1>
      <p className="mt-2 text-sm text-stone-400">
        Chúng tôi sẽ gửi email vào đúng ngày bạn đặt. Lịch âm sẽ được quy đổi sang dương lịch tự
        động.
      </p>

      {/* Add new reminder form */}
      <form
        action={async (fd) => {
          "use server";
          await createReminderAction(fd);
        }}
        className="mt-8 rounded-2xl border border-stone-800 bg-stone-950/60 p-6"
      >
        <h2 className="mb-4 font-serif text-lg text-stone-100">Thêm nhắc nhở mới</h2>
        <div className="grid gap-4 md:grid-cols-2">
          <div className="md:col-span-2">
            <label className="mb-1 block text-xs tracking-wide text-stone-500 uppercase">
              Tiêu đề
            </label>
            <input
              type="text"
              name="title"
              required
              maxLength={120}
              placeholder="Giỗ ông nội, Sinh nhật mẹ..."
              className="w-full rounded-md border border-stone-700 bg-stone-900 px-3 py-2 text-sm text-stone-100 outline-none focus:border-amber-500"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs tracking-wide text-stone-500 uppercase">
              Ngày
            </label>
            <DateInput name="date" required defaultValue={todayISO} />
          </div>
          <div>
            <label className="mb-1 block text-xs tracking-wide text-stone-500 uppercase">
              Lặp lại
            </label>
            <select
              name="recurrence"
              defaultValue=""
              className="w-full rounded-md border border-stone-700 bg-stone-900 px-3 py-2 text-sm text-stone-100 outline-none focus:border-amber-500"
            >
              <option value="">Không lặp</option>
              <option value="yearly">Hằng năm</option>
              <option value="monthly">Hằng tháng</option>
            </select>
          </div>
          <div className="flex items-center gap-2 md:col-span-2">
            <input
              type="checkbox"
              name="isLunar"
              id="isLunar"
              className="h-4 w-4 rounded border-stone-700 bg-stone-900 accent-amber-500"
            />
            <label htmlFor="isLunar" className="text-sm text-stone-300">
              Ngày này là <strong>lịch âm</strong>
            </label>
          </div>
        </div>
        <button
          type="submit"
          className="mt-5 inline-flex items-center gap-2 rounded-md bg-amber-500 px-4 py-2 text-sm font-medium text-stone-950 hover:bg-amber-400"
        >
          <Plus className="h-4 w-4" />
          Thêm nhắc nhở
        </button>
      </form>

      {/* List */}
      <div className="mt-8 space-y-3">
        {reminders.length === 0 ? (
          <p className="rounded-2xl border border-dashed border-stone-800 px-6 py-12 text-center text-sm text-stone-500">
            Bạn chưa có nhắc nhở nào.
          </p>
        ) : (
          reminders.map((r) => (
            <div
              key={r.id}
              className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-stone-800 bg-stone-950/60 px-4 py-3"
            >
              <div className="min-w-0 flex-1">
                <div className="truncate font-medium text-stone-100">{r.title}</div>
                <div className="mt-1 text-xs text-stone-400">
                  {formatDate(r.reminderDate, r.isLunar)}
                  {r.recurrence ? (
                    <span className="ml-2 rounded bg-stone-800 px-1.5 py-0.5 text-stone-300">
                      {RECURRENCE_LABEL[r.recurrence] ?? r.recurrence}
                    </span>
                  ) : null}
                  {r.notified ? <span className="ml-2 text-amber-500">· đã gửi</span> : null}
                </div>
              </div>
              <form action={deleteReminderAction}>
                <input type="hidden" name="id" value={r.id} />
                <button
                  type="submit"
                  className="rounded-md border border-stone-800 p-2 text-stone-400 hover:border-red-500/50 hover:text-red-400"
                  title="Xóa"
                  aria-label="Xóa nhắc nhở"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </form>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
