import { CheckCircle2, CircleAlert } from "lucide-react";
import { AppShell } from "@/components/AppShell";
import { EmptyState } from "@/components/EmptyState";
import { PageHeader } from "@/components/PageHeader";
import { confirmImportAction, previewImportAction } from "@/app/actions";
import { currency } from "@/lib/format";
import { getSelectedProject } from "@/lib/projects";
import { prisma } from "@/lib/prisma";

export default async function ImportPage({
  searchParams
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = (await searchParams) ?? {};
  const selected = typeof params.projectId === "string" ? params.projectId : undefined;
  const batchId = typeof params.batchId === "string" ? params.batchId : undefined;
  const imported = typeof params.imported === "string";
  const { user, projects, project, permissions, projectRole } = await getSelectedProject(selected, "expenses.create");
  const canEdit = Boolean(permissions?.["expenses.create"]);
  const batch = batchId
    ? await prisma.importBatch.findUnique({
        where: { id: batchId },
        include: { rows: { orderBy: [{ sheetName: "asc" }, { rowNumber: "asc" }] } }
      })
    : null;

  if (!project) {
    return (
      <AppShell projects={projects} username={user.name ?? user.username ?? user.email} role={projectRole ?? user.role} permissions={permissions}>
        <EmptyState title="Create a project before importing a workbook." href="/projects" actionLabel="Create project" />
      </AppShell>
    );
  }

  return (
    <AppShell projects={projects} selectedProjectId={project.id} username={user.name ?? user.username ?? user.email} role={projectRole ?? user.role} permissions={permissions}>
      <PageHeader title="Import Spreadsheet" description="Upload Purchased.xlsx, review detected rows, then import into the selected project." />

      {imported ? (
        <div className="mb-4 flex items-center gap-2 rounded-md border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
          <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
          Import completed.
        </div>
      ) : null}

      {canEdit ? (
        <form action={previewImportAction} className="panel mb-6 grid gap-4 p-4">
          <input type="hidden" name="projectId" value={project.id} />
          <label className="grid gap-2">
            <span className="label">Spreadsheet file</span>
            <input className="field" name="file" type="file" accept=".xlsx,.xls" required />
          </label>
          <button className="btn-primary">Preview import</button>
        </form>
      ) : null}

      {batch ? (
        <section className="panel overflow-hidden">
          <div className="flex flex-col gap-2 border-b border-line px-4 py-3 md:flex-row md:items-center md:justify-between">
            <div>
              <h3 className="font-semibold text-ink">{batch.fileName}</h3>
              <p className="text-sm text-slate-600">{batch.sheetNames} - {batch.rowCount} detected rows</p>
            </div>
            {canEdit ? (
              <form action={confirmImportAction}>
                <input type="hidden" name="projectId" value={project.id} />
                <input type="hidden" name="batchId" value={batch.id} />
                <button className="btn-primary">Confirm import</button>
              </form>
            ) : null}
          </div>
          <div className="overflow-x-auto">
            <table className="w-full min-w-[980px]">
              <thead className="table-head">
                <tr>
                  <th className="px-3 py-2">Status</th>
                  <th className="px-3 py-2">Sheet</th>
                  <th className="px-3 py-2">Row</th>
                  <th className="px-3 py-2">Date</th>
                  <th className="px-3 py-2">Paid / Handled By</th>
                  <th className="px-3 py-2">Category</th>
                  <th className="px-3 py-2">Description</th>
                  <th className="px-3 py-2">Amount</th>
                  <th className="px-3 py-2">Discount</th>
                  <th className="px-3 py-2">Final</th>
                </tr>
              </thead>
              <tbody>
                {batch.rows.map((row) => {
                  const mapped = JSON.parse(row.mappedJson) as {
                    date: string | null;
                    paidByName: string | null;
                    categoryName: string;
                    description: string | null;
                    amount: number;
                    discount: number;
                    finalCost: number;
                  };
                  const statusClass =
                    row.status === "READY"
                      ? "text-blue-700"
                      : row.status === "IMPORTED"
                        ? "text-emerald-700"
                        : row.status === "DUPLICATE"
                          ? "text-amber-700"
                          : "text-slate-600";
                  return (
                    <tr key={row.id}>
                      <td className={`table-cell font-semibold ${statusClass}`}>{row.status.toLowerCase()}</td>
                      <td className="table-cell">{row.sheetName}</td>
                      <td className="table-cell">{row.rowNumber}</td>
                      <td className="table-cell">{mapped.date ?? "-"}</td>
                      <td className="table-cell">{mapped.paidByName ?? "-"}</td>
                      <td className="table-cell">{mapped.categoryName}</td>
                      <td className="table-cell">{mapped.description ?? row.reason ?? "-"}</td>
                      <td className="table-cell">{currency(mapped.amount)}</td>
                      <td className="table-cell">{currency(mapped.discount)}</td>
                      <td className="table-cell font-semibold text-ink">{currency(mapped.finalCost)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </section>
      ) : (
        <div className="panel flex items-start gap-3 p-4 text-sm text-slate-700">
          <CircleAlert className="mt-0.5 h-4 w-4 text-blue-700" aria-hidden="true" />
          <p>The import detects sheets such as Deposit, One time payment, Renovation, and Sheet1, then maps payment handler, category, amount, discount/tax return, final cost, notes, and receipt links into expenses.</p>
        </div>
      )}
    </AppShell>
  );
}
