import Link from "next/link";
import { and, eq, asc } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { canEditCatalog } from "@/lib/rbac";
import { db } from "@/db";
import {
  products,
  productGroups,
  technologies,
  channels,
  territories,
  programs,
  targets,
  users,
} from "@/db/schema";
import { formatVnd, formatNumber, ROLE_LABEL, PRODUCT_ROLE_LABEL, formatPeriod } from "@/lib/format";
import { PageHeader, TableWrap, SectionTitle, Badge, EmptyState } from "@/components/ui";
import { monthKey, today } from "@/lib/period";

export const dynamic = "force-dynamic";

export default async function CatalogPage() {
  const session = await requireSession();

  if (!canEditCatalog(session)) {
    return (
      <>
        <PageHeader title="Danh mục" />
        <EmptyState
          message="Bạn không có quyền xem danh mục."
          hint="Chức năng này dành cho Ban giám đốc và Quản lý vùng."
        />
      </>
    );
  }

  const tenantId = session.tenantId;
  const period = monthKey(today());

  const [productRows, groupRows, techRows, channelRows, territoryRows, programRows, targetRows, userRows] =
    await Promise.all([
      db
        .select({
          id: products.id,
          code: products.code,
          name: products.name,
          unit: products.unit,
          volume: products.volume,
          note: products.note,
          unitPrice: products.unitPrice,
          retailPrice: products.retailPrice,
          discountPercent: products.discountPercent,
          role: products.role,
          isActive: products.isActive,
          groupName: productGroups.name,
          techName: technologies.name,
        })
        .from(products)
        .leftJoin(productGroups, eq(products.groupId, productGroups.id))
        .leftJoin(technologies, eq(products.technologyId, technologies.id))
        .where(eq(products.tenantId, tenantId))
        .orderBy(asc(products.code)),
      db.select().from(productGroups).where(eq(productGroups.tenantId, tenantId)),
      db.select().from(technologies).where(eq(technologies.tenantId, tenantId)),
      db.select().from(channels).where(eq(channels.tenantId, tenantId)),
      db
        .select({ id: territories.id, name: territories.name, level: territories.level, parentId: territories.parentId })
        .from(territories)
        .where(eq(territories.tenantId, tenantId))
        .orderBy(asc(territories.code)),
      db.select().from(programs).where(eq(programs.tenantId, tenantId)),
      db
        .select({
          id: targets.id,
          periodKey: targets.periodKey,
          scopeType: targets.scopeType,
          scopeId: targets.scopeId,
          revenueTarget: targets.revenueTarget,
          orderTarget: targets.orderTarget,
        })
        .from(targets)
        .where(and(eq(targets.tenantId, tenantId), eq(targets.periodKey, period))),
      db
        .select({ id: users.id, fullName: users.fullName, email: users.email, role: users.role, isActive: users.isActive })
        .from(users)
        .where(eq(users.tenantId, tenantId))
        .orderBy(asc(users.role), asc(users.fullName)),
    ]);

  const userName = new Map(userRows.map((u) => [u.id, u.fullName]));
  const regions = territoryRows.filter((t) => t.level === "REGION");

  return (
    <>
      <PageHeader
        title="Danh mục"
        subtitle="Sản phẩm, kênh bán, khu vực, chương trình và chỉ tiêu — nền dữ liệu cho toàn bộ báo cáo."
        actions={
          <>
            <Link href="/danh-muc/phong-ban" className="btn-ghost">
              Phòng ban
            </Link>
            <Link href="/danh-muc/khu-vuc" className="btn-ghost">
              Khu vực
            </Link>
            <Link href="/danh-muc/su-kien" className="btn-ghost">
              Chuyên đề
            </Link>
            <Link href="/danh-muc/su-kien-moi-khach" className="btn-ghost">
              Mời khách sự kiện
            </Link>
            <Link href="/danh-muc/khoa-hoc" className="btn-ghost">
              Khóa học
            </Link>
            <Link href="/danh-muc/nhat-ky" className="btn-ghost">
              Nhật ký
            </Link>
            <Link href="/danh-muc/nhan-vien" className="btn-ghost">
              Nhân viên
            </Link>
            <Link href="/danh-muc/nhan-vien?tab=chuyen-mon" className="btn-ghost">
              Nhân viên chuyên môn
            </Link>
            <Link href="/danh-muc/nguoi-dung" className="btn-ghost">
              Người dùng
            </Link>
            <Link href="/danh-muc/nhap-excel" className="btn-ghost">
              Nhập từ Excel
            </Link>
            <Link href="/danh-muc/kpi-tu-tao" className="btn-ghost">
              KPI tự tạo
            </Link>
            <Link href="/danh-muc/cai-dat" className="btn-ghost">
              Cài đặt chung
            </Link>
            <Link href="/danh-muc/thong-bao" className="btn-ghost">
              Thông báo
            </Link>
            <Link href="/danh-muc/chi-tieu" className="btn-primary">
              Giao chỉ tiêu
            </Link>
          </>
        }
      />

      <div className="mb-6 grid gap-4 lg:grid-cols-3">
        <div className="card p-4">
          <SectionTitle>Kênh bán</SectionTitle>
          <ul className="flex flex-col gap-1.5 text-sm">
            {channelRows.map((channel) => (
              <li key={channel.id} className="flex justify-between">
                <span className="text-ink-700">{channel.name}</span>
                <span className="tnum text-xs text-ink-400">{channel.code}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="card p-4">
          <SectionTitle hint={`${territoryRows.length} đơn vị`}>
            <Link href="/danh-muc/khu-vuc" className="hover:text-brand-600">
              Khu vực →
            </Link>
          </SectionTitle>
          <ul className="flex flex-col gap-2 text-sm">
            {regions.map((region) => (
              <li key={region.id}>
                <div className="font-semibold text-ink-700">{region.name}</div>
                <div className="text-xs text-ink-400">
                  {territoryRows
                    .filter((t) => t.parentId === region.id)
                    .map((t) => t.name)
                    .join(" · ")}
                </div>
              </li>
            ))}
          </ul>
        </div>

        <div className="card p-4">
          <SectionTitle hint={`${groupRows.length} nhóm · ${techRows.length} công nghệ`}>
            Nhóm &amp; công nghệ
          </SectionTitle>
          <div className="flex flex-wrap gap-1.5">
            {groupRows.map((group) => (
              <Badge key={group.id} tone="brand">
                {group.name}
              </Badge>
            ))}
            {techRows.map((tech) => (
              <Badge key={tech.id}>{tech.name}</Badge>
            ))}
          </div>
        </div>
      </div>

      <SectionTitle hint={`${productRows.length} sản phẩm`}>Sản phẩm</SectionTitle>
      <TableWrap>
        <thead>
          <tr>
            <th>Mã</th>
            <th>Tên sản phẩm</th>
            <th>Nhóm</th>
            <th>Công nghệ</th>
            <th>Vai trò</th>
            <th>ĐVT</th>
            <th>Dung tích / TL</th>
            <th className="text-right">Giá đại lý</th>
            <th className="text-right">Giá bán lẻ</th>
            <th className="text-right">Chiết khấu</th>
            <th>Ghi chú</th>
          </tr>
        </thead>
        <tbody>
          {productRows.map((product) => (
            <tr key={product.id}>
              <td className="tnum text-ink-400">{product.code}</td>
              <td className="font-medium text-ink-700">{product.name}</td>
              <td className="text-ink-500">{product.groupName ?? "—"}</td>
              <td className="text-ink-500">{product.techName ?? "—"}</td>
              <td>
                <Badge tone={product.role === "CORE" ? "brand" : product.role === "RECOVERY" ? "red" : "neutral"}>
                  {PRODUCT_ROLE_LABEL[product.role]}
                </Badge>
              </td>
              <td className="text-ink-500">{product.unit}</td>
              <td className="text-ink-500">{product.volume ?? "—"}</td>
              <td className="tnum text-right font-medium">{formatVnd(Number(product.unitPrice))}</td>
              <td className="tnum text-right text-ink-500">
                {Number(product.retailPrice) > 0 ? formatVnd(Number(product.retailPrice)) : "—"}
              </td>
              <td className="tnum text-right text-ink-500">
                {Number(product.discountPercent) > 0 ? `${product.discountPercent}%` : "—"}
              </td>
              <td className="max-w-xs text-xs text-ink-500">{product.note ?? "—"}</td>
            </tr>
          ))}
        </tbody>
      </TableWrap>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <div>
          <SectionTitle hint="theo dõi tiến độ riêng ở báo cáo">Chương trình bán hàng</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Chương trình</th>
                <th>Loại</th>
                <th className="text-right">Mục tiêu DT</th>
                <th className="text-right">Mục tiêu SL</th>
              </tr>
            </thead>
            <tbody>
              {programRows.map((program) => (
                <tr key={program.id}>
                  <td className="font-medium text-ink-700">{program.name}</td>
                  <td>
                    <Badge tone={program.type === "NEW_PRODUCT" ? "gold" : "brand"}>
                      {{ NEW_PRODUCT: "SP mới", FOCUS_PRODUCT: "SP trọng tâm", CAMPAIGN: "Chiến dịch" }[program.type]}
                    </Badge>
                  </td>
                  <td className="tnum text-right">{formatVnd(Number(program.revenueTarget ?? 0))}</td>
                  <td className="tnum text-right text-ink-500">{formatNumber(program.qtyTarget ?? 0)}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>

        <div>
          <SectionTitle hint={formatPeriod(period)}>Chỉ tiêu kế hoạch tháng</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Phạm vi</th>
                <th className="text-right">Chỉ tiêu doanh thu</th>
                <th className="text-right">Chỉ tiêu đơn</th>
              </tr>
            </thead>
            <tbody>
              {targetRows.length === 0 && (
                <tr>
                  <td colSpan={3} className="py-8 text-center text-ink-400">
                    Chưa giao chỉ tiêu cho kỳ này.
                  </td>
                </tr>
              )}
              {targetRows.map((target) => (
                <tr key={target.id}>
                  <td className="text-ink-700">
                    {target.scopeType === "COMPANY"
                      ? "Toàn công ty"
                      : target.scopeType === "USER"
                        ? (userName.get(target.scopeId ?? "") ?? "Nhân viên")
                        : target.scopeType}
                  </td>
                  <td className="tnum text-right font-medium">{formatVnd(Number(target.revenueTarget))}</td>
                  <td className="tnum text-right text-ink-500">{target.orderTarget}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
      </div>

      <div className="mt-6">
        <SectionTitle hint={`${userRows.length} tài khoản`}>
          <Link href="/danh-muc/nguoi-dung" className="hover:text-brand-600">
            Người dùng &amp; phân quyền →
          </Link>
        </SectionTitle>
        <TableWrap>
          <thead>
            <tr>
              <th>Họ tên</th>
              <th>Email</th>
              <th>Vai trò</th>
              <th>Trạng thái</th>
            </tr>
          </thead>
          <tbody>
            {userRows.map((user) => (
              <tr key={user.id}>
                <td className="font-medium text-ink-700">{user.fullName}</td>
                <td className="text-ink-500">{user.email}</td>
                <td>
                  <Badge
                    tone={
                      user.role === "DIRECTOR"
                        ? "brand"
                        : user.role === "GDKV"
                          ? "green"
                          : user.role === "MANAGER"
                            ? "gold"
                            : "neutral"
                    }
                  >
                    {ROLE_LABEL[user.role]}
                  </Badge>
                </td>
                <td>
                  {user.isActive ? <Badge tone="green">Đang hoạt động</Badge> : <Badge tone="red">Đã khoá</Badge>}
                </td>
              </tr>
            ))}
          </tbody>
        </TableWrap>
      </div>
    </>
  );
}
