import Link from "next/link";
import { and, eq, sql } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { planItems, weeklyPlans, dailyReports, checkIns, customers } from "@/db/schema";
import { today } from "@/lib/period";
import { formatDate } from "@/lib/format";
import { PageHeader } from "@/components/ui";
import { TodayClient, type TodayItem } from "./today-client";
import { vnDate } from "@/lib/sql-dates";

export const dynamic = "force-dynamic";

/**
 * Màn hình NVKD dùng hằng ngày ngoài thị trường.
 *
 * Tối ưu cho điện thoại: chỉ lộ trình hôm nay và ô nhập báo cáo, không có bảng
 * biểu hay biểu đồ. Mục tiêu là xong việc trong dưới một phút.
 */
export default async function TodayPage() {
  const session = await requireSession();
  const workDate = today();

  const items = await db
    .select({
      id: planItems.id,
      content: planItems.content,
      objective: planItems.objective,
      timeSlot: planItems.timeSlot,
      status: planItems.status,
      customerId: planItems.customerId,
      customerName: customers.orgName,
      customerAddress: customers.address,
    })
    .from(planItems)
    .innerJoin(weeklyPlans, eq(planItems.planId, weeklyPlans.id))
    .leftJoin(customers, eq(planItems.customerId, customers.id))
    .where(
      and(
        eq(planItems.tenantId, session.tenantId),
        eq(weeklyPlans.userId, session.userId),
        eq(planItems.planDate, workDate),
      ),
    )
    .orderBy(planItems.sortOrder, planItems.timeSlot);

  const [report] = await db
    .select({
      content: dailyReports.content,
      results: dailyReports.results,
      proposals: dailyReports.proposals,
      pending: dailyReports.pending,
      nextSteps: dailyReports.nextSteps,
      routeCompliant: dailyReports.routeCompliant,
    })
    .from(dailyReports)
    .where(
      and(
        eq(dailyReports.tenantId, session.tenantId),
        eq(dailyReports.userId, session.userId),
        eq(dailyReports.reportDate, workDate),
      ),
    )
    .limit(1);

  // Đếm check-in bằng truy vấn gộp riêng — xem chú thích trong CLAUDE.md về
  // truy vấn con tương quan sinh SQL thiếu tên bảng.
  const checkedInItems = await db
    .select({ planItemId: checkIns.planItemId })
    .from(checkIns)
    .where(
      and(
        eq(checkIns.tenantId, session.tenantId),
        eq(checkIns.userId, session.userId),
        sql`${vnDate(checkIns.checkedAt)} = ${workDate}`,
      ),
    );

  const checkedInSet = new Set(checkedInItems.map((row) => row.planItemId).filter(Boolean));

  const todayItems: TodayItem[] = items.map((item) => ({
    id: item.id,
    content: item.content,
    objective: item.objective,
    timeSlot: item.timeSlot,
    status: item.status,
    customerId: item.customerId,
    customerName: item.customerName,
    customerAddress: item.customerAddress,
    checkedIn: checkedInSet.has(item.id),
  }));

  return (
    <>
      <PageHeader
        title="Hôm nay"
        subtitle={`${formatDate(workDate)} · ${session.fullName}`}
        actions={
          <>
            <Link href="/cong-viec/chot-tuan" className="btn-ghost">
              Tổng kết tuần
            </Link>
            <Link href="/cong-viec" className="btn-ghost">
              Xem cả tuần
            </Link>
          </>
        }
      />
      <TodayClient items={todayItems} reportDate={workDate} existingReport={report ?? null} />
    </>
  );
}
