import { Card } from "@/components/ui/card";
import { env } from "@/lib/env";
import { getLocalDb } from "@/lib/local-db";
import { createClient } from "@/lib/supabase/server";
import { formatInteger } from "@/lib/utils";

type ImportRow = {
  id: number;
  uploaded_by: string;
  file_name: string;
  detected_country_code: string | null;
  status: string;
  total_rows: number;
  inserted_rows: number;
  updated_rows: number;
  failed_rows: number;
  error_summary: string | null;
  created_at: string;
};

type ProfileRow = {
  id: string;
  email: string;
};

export default async function AdminImportsPage() {
  let imports: ImportRow[] = [];
  let profiles: ProfileRow[] = [];

  if (!env.hasSupabasePublicEnv) {
    const db = await getLocalDb();
    imports = [...(db.imports as ImportRow[])].sort(
      (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
    );
    profiles = [{ id: "00000000-0000-0000-0000-000000000000", email: "local-admin@internal" }];
  } else {
    const supabase = await createClient();
    const [importsRes, profilesRes] = await Promise.all([
      supabase
        .from("imports")
        .select(
          "id, uploaded_by, file_name, detected_country_code, status, total_rows, inserted_rows, updated_rows, failed_rows, error_summary, created_at",
        )
        .order("created_at", { ascending: false })
        .limit(100),
      supabase.from("profiles").select("id, email"),
    ]);

    if (importsRes.error) throw new Error(importsRes.error.message);
    if (profilesRes.error) throw new Error(profilesRes.error.message);

    imports = (importsRes.data ?? []) as ImportRow[];
    profiles = (profilesRes.data ?? []) as ProfileRow[];
  }

  const emailByUserId = new Map(profiles.map((profile) => [profile.id, profile.email]));

  return (
    <div className="space-y-4">
      <Card>
        <h2 className="text-lg font-semibold text-slate-900">VEEVA Import Review</h2>
        <p className="mt-2 text-sm text-slate-600">
          Every uploaded Otsuka workbook is tracked here, including merge counts and parser/access errors.
        </p>
        {!env.hasSupabasePublicEnv ? (
          <p className="mt-2 text-xs font-medium text-[#2663AC]">
            Local mode active: data source is <code>data/local-db.json</code>.
          </p>
        ) : null}
      </Card>

      <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white">
        <div className="max-h-[720px] overflow-auto">
          <table className="w-full text-left text-sm">
            <thead className="sticky top-0 bg-slate-50 text-[11px] uppercase tracking-[0.16em] text-slate-500">
              <tr>
                <th className="px-4 py-3">Import</th>
                <th className="px-4 py-3">Uploader</th>
                <th className="px-4 py-3">Country</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Rows</th>
                <th className="px-4 py-3">Result</th>
                <th className="px-4 py-3">Errors</th>
              </tr>
            </thead>
            <tbody>
              {imports.map((item) => (
                <tr key={item.id} className="border-t border-slate-200 align-top">
                  <td className="px-4 py-3">
                    <p className="font-medium text-slate-800">#{item.id}</p>
                    <p className="text-xs text-slate-500">{item.file_name}</p>
                    <p className="text-xs text-slate-500">
                      {new Date(item.created_at).toLocaleString("en-GB")}
                    </p>
                  </td>
                  <td className="px-4 py-3 text-slate-600">
                    {emailByUserId.get(item.uploaded_by) ?? item.uploaded_by}
                  </td>
                  <td className="px-4 py-3 text-slate-600">{item.detected_country_code ?? "-"}</td>
                  <td className="px-4 py-3 text-slate-800">{item.status}</td>
                  <td className="px-4 py-3 text-slate-800">{formatInteger(item.total_rows)}</td>
                  <td className="px-4 py-3 text-xs text-slate-600">
                    <p>{formatInteger(item.inserted_rows)} inserted</p>
                    <p>{formatInteger(item.updated_rows)} updated</p>
                    <p>{formatInteger(item.failed_rows)} failed</p>
                  </td>
                  <td className="max-w-[420px] px-4 py-3 text-xs text-slate-500">
                    {item.error_summary ? (
                      <pre className="whitespace-pre-wrap font-mono text-[11px]">{item.error_summary}</pre>
                    ) : (
                      "None"
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
