import { headers } from "next/headers";
import Link from "next/link";
import { redirect } from "next/navigation";
import { BookOpen, MessageSquare, Bell, Sparkles, Plus, Calendar, Eye } from "lucide-react";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { SignOutButton } from "./sign-out";

export const dynamic = "force-dynamic";

const TOOL_LABEL: Record<string, string> = {
  "van-menh": 'Vận mệnh "Thầy"',
  "kinh-dich": 'Kinh Dịch "Thầy"',
  "giai-mong": "Giải mộng",
  "tu-vi": "Tử vi",
  "tu-vi-tron-doi": "Tử vi trọn đời",
  "phong-thuy-nha": "Phong thủy nhà",
  "ngay-tot": "Ngày tốt",
};

function relativeVi(d: Date): string {
  const ms = Date.now() - d.getTime();
  const min = Math.floor(ms / 60000);
  if (min < 1) return "vừa xong";
  if (min < 60) return `${min} phút trước`;
  const hr = Math.floor(min / 60);
  if (hr < 24) return `${hr} giờ trước`;
  const day = Math.floor(hr / 24);
  if (day < 30) return `${day} ngày trước`;
  return d.toLocaleDateString("vi-VN", { day: "2-digit", month: "short", year: "numeric" });
}

function dateVi(d: Date, includeYear = true): string {
  return d.toLocaleDateString(
    "vi-VN",
    includeYear
      ? { weekday: "long", day: "2-digit", month: "long", year: "numeric" }
      : { day: "2-digit", month: "long" }
  );
}

export default async function MePage() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    redirect("/login");
  }

  const userId = session.user.id;
  const [
    chartCount,
    conversationCount,
    reminderCount,
    upcomingReminder,
    recentCharts,
    recentConversations,
  ] = await Promise.all([
    prisma.chart.count({ where: { userId } }),
    prisma.aIConversation.count({ where: { userId } }),
    prisma.reminder.count({ where: { userId } }),
    prisma.reminder.findFirst({
      where: { userId, reminderDate: { gte: new Date() } },
      orderBy: { reminderDate: "asc" },
      select: { title: true, reminderDate: true, isLunar: true },
    }),
    prisma.chart.findMany({
      where: { userId },
      orderBy: { updatedAt: "desc" },
      take: 4,
      select: {
        id: true,
        label: true,
        fullName: true,
        gender: true,
        birthDate: true,
        isDefault: true,
        shareToken: true,
        updatedAt: true,
      },
    }),
    prisma.aIConversation.findMany({
      where: { userId },
      orderBy: { updatedAt: "desc" },
      take: 4,
      select: { id: true, title: true, toolKey: true, updatedAt: true },
    }),
  ]);

  return (
    <div className="mx-auto max-w-5xl px-4 py-12">
      {/* Header */}
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          <h1 className="font-serif text-4xl font-semibold text-stone-100">
            Chào {session.user.name}
          </h1>
          <p className="mt-1 text-stone-400">{session.user.email}</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link
            href="/tu-vi-tron-doi"
            className="inline-flex items-center gap-1.5 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" />
            Lập lá số mới
          </Link>
          <Link
            href="/van-menh"
            className="inline-flex items-center gap-1.5 rounded-md border border-stone-700 px-4 py-2 text-sm text-stone-200 hover:border-amber-500/40"
          >
            <Sparkles className="h-4 w-4" />
            Hỏi &ldquo;Thầy&rdquo;
          </Link>
        </div>
      </div>

      {/* Stats row */}
      <div className="mt-8 grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard
          icon={<BookOpen className="h-5 w-5 text-amber-500" />}
          label="Lá số"
          value={chartCount}
          href="/la-so"
        />
        <StatCard
          icon={<MessageSquare className="h-5 w-5 text-amber-500" />}
          label='Hội thoại "Thầy"'
          value={conversationCount}
          href={conversationCount > 0 ? "/thu-vien-ai" : "/van-menh"}
        />
        <StatCard
          icon={<Bell className="h-5 w-5 text-amber-500" />}
          label="Nhắc nhở"
          value={reminderCount}
          href="/me/reminders"
        />
        <StatCard
          icon={<Calendar className="h-5 w-5 text-amber-500" />}
          label="Sắp tới"
          value={upcomingReminder ? "1" : "—"}
          subtitle={
            upcomingReminder
              ? dateVi(upcomingReminder.reminderDate, false) +
                (upcomingReminder.isLunar ? " (âm)" : "")
              : "không có"
          }
          href="/me/reminders"
        />
      </div>

      {/* Two-column body */}
      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        {/* Recent charts */}
        <section className="rounded-2xl border border-stone-800 bg-stone-950/60 p-6">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-serif text-xl text-stone-100">Lá số gần đây</h2>
            {chartCount > 0 ? (
              <Link href="/la-so" className="text-xs text-amber-500 hover:underline">
                Xem tất cả →
              </Link>
            ) : null}
          </div>
          {recentCharts.length === 0 ? (
            <EmptyState
              text="Chưa có lá số nào. Lập lá số đầu tiên để bắt đầu."
              cta={
                <Link
                  href="/tu-vi-tron-doi"
                  className="mt-3 inline-flex rounded-md bg-amber-500 px-4 py-2 text-sm font-medium text-stone-950"
                >
                  Lập lá số mới
                </Link>
              }
            />
          ) : (
            <ul className="divide-y divide-stone-800">
              {recentCharts.map((c) => (
                <li key={c.id} className="flex items-center justify-between gap-3 py-3">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="truncate font-medium text-stone-100">{c.label}</span>
                      {c.isDefault ? (
                        <span className="rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] text-amber-500 uppercase">
                          Mặc định
                        </span>
                      ) : null}
                      {c.shareToken ? (
                        <span title="Đang chia sẻ công khai">
                          <Eye className="h-3.5 w-3.5 text-emerald-500" />
                        </span>
                      ) : null}
                    </div>
                    <div className="mt-0.5 truncate text-xs text-stone-500">
                      {c.fullName} ·{" "}
                      {c.birthDate.toLocaleDateString("vi-VN", {
                        day: "2-digit",
                        month: "2-digit",
                        year: "numeric",
                      })}{" "}
                      · {c.gender === "FEMALE" ? "Nữ" : "Nam"}
                    </div>
                  </div>
                  <span className="shrink-0 text-xs text-stone-500">{relativeVi(c.updatedAt)}</span>
                </li>
              ))}
            </ul>
          )}
        </section>

        {/* Recent AI conversations */}
        <section className="rounded-2xl border border-stone-800 bg-stone-950/60 p-6">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-serif text-xl text-stone-100">
              Hội thoại &ldquo;Thầy&rdquo; gần đây
            </h2>
            {conversationCount > 0 ? (
              <Link href="/thu-vien-ai" className="text-xs text-amber-500 hover:underline">
                Xem tất cả →
              </Link>
            ) : null}
          </div>
          {recentConversations.length === 0 ? (
            <EmptyState
              text='Chưa có hội thoại "Thầy" nào.'
              cta={
                <Link
                  href="/van-menh"
                  className="mt-3 inline-flex rounded-md bg-amber-500 px-4 py-2 text-sm font-medium text-stone-950"
                >
                  Bắt đầu hỏi
                </Link>
              }
            />
          ) : (
            <ul className="divide-y divide-stone-800">
              {recentConversations.map((c) => (
                <li key={c.id} className="flex items-center justify-between gap-3 py-3">
                  <div className="min-w-0 flex-1">
                    <div className="truncate font-medium text-stone-100">{c.title}</div>
                    <div className="mt-0.5 text-xs text-stone-500">
                      {TOOL_LABEL[c.toolKey] ?? c.toolKey}
                    </div>
                  </div>
                  <span className="shrink-0 text-xs text-stone-500">{relativeVi(c.updatedAt)}</span>
                </li>
              ))}
            </ul>
          )}
        </section>

        {/* Upcoming reminder full-width */}
        <section className="rounded-2xl border border-stone-800 bg-stone-950/60 p-6 lg:col-span-2">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-serif text-xl text-stone-100">Nhắc nhở sắp tới</h2>
            <Link href="/me/reminders" className="text-xs text-amber-500 hover:underline">
              Quản lý →
            </Link>
          </div>
          {upcomingReminder ? (
            <div className="flex items-start gap-4">
              <div className="rounded-full bg-amber-500/15 p-3">
                <Bell className="h-5 w-5 text-amber-500" />
              </div>
              <div className="flex-1">
                <div className="text-base font-medium text-stone-100">{upcomingReminder.title}</div>
                <div className="mt-1 text-sm text-stone-400">
                  {dateVi(upcomingReminder.reminderDate)}
                  {upcomingReminder.isLunar ? " (lịch âm)" : ""}
                </div>
              </div>
            </div>
          ) : (
            <EmptyState
              text="Không có nhắc nhở nào sắp tới. Đặt nhắc giỗ chạp, sinh nhật âm lịch để không bao giờ quên."
              cta={
                <Link
                  href="/me/reminders"
                  className="mt-3 inline-flex rounded-md bg-amber-500 px-4 py-2 text-sm font-medium text-stone-950"
                >
                  Tạo nhắc nhở
                </Link>
              }
            />
          )}
        </section>
      </div>

      <div className="mt-12 border-t border-stone-800 pt-6">
        <SignOutButton />
      </div>
    </div>
  );
}

function StatCard({
  icon,
  label,
  value,
  subtitle,
  href,
}: {
  icon: React.ReactNode;
  label: string;
  value: number | string;
  subtitle?: string;
  href: string;
}) {
  return (
    <Link
      href={href}
      className="group rounded-2xl border border-stone-800 bg-stone-950/60 p-4 transition hover:border-amber-500/40"
    >
      <div className="flex items-center gap-2">{icon}</div>
      <div className="mt-3 text-2xl font-semibold text-stone-100">{value}</div>
      <div className="mt-0.5 text-xs tracking-wide text-stone-500 uppercase">{label}</div>
      {subtitle ? <div className="mt-1 truncate text-xs text-stone-400">{subtitle}</div> : null}
    </Link>
  );
}

function EmptyState({ text, cta }: { text: string; cta?: React.ReactNode }) {
  return (
    <div className="py-6 text-center">
      <p className="text-sm text-stone-500">{text}</p>
      {cta}
    </div>
  );
}
