import { ActionForm } from "@/components/action-form";
import Link from "next/link";
import { and, eq, inArray, asc, desc } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { canEditCatalog, visibleUserIds } from "@/lib/rbac";
import { db } from "@/db";
import { customKpis, customKpiEntries, users } from "@/db/schema";
import { monthKey, today, isRealMonth } from "@/lib/period";
import { formatPeriod } from "@/lib/format";
import { PageHeader, TableWrap, EmptyState, SectionTitle, ProgressBar, Badge } from "@/components/ui";
import { CreateKpiForm, AssignKpiForm } from "./kpi-forms";
import { deactivateKpiAction, recordActualAction, deleteEntryAction } from "./actions";

export const dynamic = "force-dynamic";

export default async function CustomKpiPage({
  searchParams,
}: {
  searchParams: Promise<{ ky?: string }>;
}) {
  const session = await requireSession();
  const params = await searchParams;
  const periodKey = isRealMonth(params.ky) ? params.ky : monthKey(today());

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

  const allowedUserIds = await visibleUserIds(session);

  const [kpiRows, staffRows] = await Promise.all([
    db
      .select()
      .from(customKpis)
      .where(and(eq(customKpis.tenantId, session.tenantId), eq(customKpis.isActive, true)))
      .orderBy(asc(customKpis.name)),
    db
      .select({ id: users.id, name: users.fullName })
      .from(users)
      .where(
        and(
          eq(users.tenantId, session.tenantId),
          eq(users.isActive, true),
          eq(users.role, "SALES"),
          allowedUserIds ? inArray(users.id, allowedUserIds) : undefined,
        ),
      )
      .orderBy(asc(users.fullName)),
  ]);

  const entryRows =
    kpiRows.length === 0
      ? []
      : await db
          .select({
            id: customKpiEntries.id,
            kpiId: customKpiEntries.kpiId,
            kpiName: customKpis.name,
            kpiUnit: customKpis.unit,
            userId: customKpiEntries.userId,
            userName: users.fullName,
            targetValue: customKpiEntries.targetValue,
            actualValue: customKpiEntries.actualValue,
            note: customKpiEntries.note,
          })
          .from(customKpiEntries)
          .innerJoin(customKpis, eq(customKpiEntries.kpiId, customKpis.id))
          .innerJoin(users, eq(customKpiEntries.userId, users.id))
          .where(
            and(
              eq(customKpiEntries.tenantId, session.tenantId),
              eq(customKpiEntries.periodKey, periodKey),
              allowedUserIds ? inArray(customKpiEntries.userId, allowedUserIds) : undefined,
            ),
          )
          .orderBy(desc(customKpis.name), asc(users.fullName));

  return (
    <>
      <PageHeader
        title="KPI tự tạo"
        subtitle="Chỉ tiêu ngoài bộ số liệu cố định — quản lý tự đặt tên, giao chỉ tiêu và ghi nhận kết quả thực tế."
        actions={
          <>
            <form action="/danh-muc/kpi-tu-tao" className="flex items-end gap-2">
              <input type="month" name="ky" defaultValue={periodKey} className="input" aria-label="Chọn kỳ" />
              <button type="submit" className="btn-ghost">
                Xem
              </button>
            </form>
            <Link href="/danh-muc" className="btn-ghost">
              ← Danh mục
            </Link>
          </>
        }
      />

      <div className="mb-6">
        <SectionTitle hint={`${kpiRows.length} loại đang dùng`}>Loại KPI</SectionTitle>
        <CreateKpiForm />
        {kpiRows.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-2">
            {kpiRows.map((kpi) => (
              <div
                key={kpi.id}
                className="flex items-center gap-2 rounded-full border border-[var(--color-line)] bg-white px-3 py-1 text-xs"
              >
                <span className="font-medium text-ink-700">{kpi.name}</span>
                <span className="text-ink-400">({kpi.unit})</span>
                <ActionForm action={deactivateKpiAction} success="Đã ngừng KPI." confirm="Ngừng KPI này? KPI sẽ không còn nằm trong danh sách đang dùng.">
                  <input type="hidden" name="id" value={kpi.id} />
                  <button type="submit" className="text-ink-300 hover:text-red-600">
                    ✕
                  </button>
                </ActionForm>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="mb-6">
        <SectionTitle>Giao chỉ tiêu {formatPeriod(periodKey)}</SectionTitle>
        <AssignKpiForm
          periodKey={periodKey}
          kpis={kpiRows.map((k) => ({ id: k.id, name: k.name, unit: k.unit }))}
          staff={staffRows}
        />
      </div>

      <div>
        <SectionTitle hint={`${entryRows.length} chỉ tiêu đã giao`}>
          Kết quả {formatPeriod(periodKey)}
        </SectionTitle>
        {entryRows.length === 0 ? (
          <EmptyState
            message="Chưa giao KPI tự tạo nào cho kỳ này."
            hint="Tạo KPI và giao chỉ tiêu ở hai mục phía trên."
          />
        ) : (
          <TableWrap>
            <thead>
              <tr>
                <th>KPI</th>
                <th>Nhân viên</th>
                <th className="text-right">Chỉ tiêu</th>
                <th style={{ width: 220 }}>Kết quả thực tế</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {entryRows.map((row) => {
                const pct = row.targetValue > 0 ? (row.actualValue / row.targetValue) * 100 : null;
                return (
                  <tr key={row.id}>
                    <td className="font-medium text-ink-700">{row.kpiName}</td>
                    <td className="text-ink-600">{row.userName}</td>
                    <td className="tnum text-right text-ink-500">
                      {row.targetValue} {row.kpiUnit}
                    </td>
                    <td>
                      <ActionForm action={recordActualAction} success="Đã ghi nhận số thực hiện." className="flex items-center gap-1.5">
                        <input type="hidden" name="entryId" value={row.id} />
                        <input
                          name="actualValue"
                          type="number"
                          min={0}
                          step="any"
                          defaultValue={row.actualValue}
                          className="input tnum w-20 py-1 text-sm"
                          aria-label={`Kết quả ${row.kpiName} của ${row.userName}`}
                        />
                        <input
                          name="note"
                          defaultValue={row.note ?? ""}
                          placeholder="Ghi chú…"
                          className="input w-28 py-1 text-sm"
                        />
                        <button type="submit" className="btn-ghost px-2 py-1 text-xs">
                          Lưu
                        </button>
                      </ActionForm>
                      {pct != null && (
                        <div className="mt-1.5">
                          <ProgressBar percent={pct} />
                        </div>
                      )}
                    </td>
                    <td className="text-right">
                      {pct != null && (
                        <Badge tone={pct >= 100 ? "green" : pct >= 60 ? "gold" : "red"}>
                          {Math.round(pct)}%
                        </Badge>
                      )}
                      <ActionForm action={deleteEntryAction} success="Đã xoá dòng chỉ tiêu." confirm="Xoá dòng chỉ tiêu này?" className="mt-1">
                        <input type="hidden" name="id" value={row.id} />
                        <button type="submit" className="text-[11px] text-ink-300 hover:text-red-600">
                          Xoá
                        </button>
                      </ActionForm>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </TableWrap>
        )}
      </div>
    </>
  );
}
