"use client";

import * as React from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { Download, Printer } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { FilterSelect } from "@/components/ui/data-table";
import { HBarChart, CHART_COLORS } from "@/components/ui/charts";
import { fmtMoney, fmtNumber } from "@/lib/format";
import { RESERVATION_SOURCES, RESERVATION_SOURCE_META, RESERVATION_STATUSES, RESERVATION_STATUS_META } from "@/lib/domain";

export interface ReportDef {
  title: string;
  columns: { key: string; label: string; align?: "left" | "right"; money?: boolean }[];
  rows: Record<string, string | number>[];
  summary: { label: string; value: string | number; money?: boolean }[];
  chart?: { key: string; label: string; nameKey: string; money?: boolean };
}

const LABELS: Record<string, string> = { reservations: "Reservations", occupancy: "Occupancy", revenue: "Revenue", expenses: "Expenses", profit: "Profit", apartments: "Apartment performance", workers: "Worker performance", commissions: "Commissions", customers: "Customers" };

export function ReportView({ type, types, report, currency, periodLabel, workers, filters, businessName }: { type: string; types: string[]; report: ReportDef; currency: string; periodLabel: string; workers: { id: string; fullName: string }[]; filters: { worker?: string; source?: string; status?: string }; businessName: string }) {
  const router = useRouter();
  const pathname = usePathname();
  const sp = useSearchParams();
  const set = (k: string, v: string) => {
    const next = new URLSearchParams(sp.toString());
    if (v) next.set(k, v);
    else next.delete(k);
    router.replace(`${pathname}?${next.toString()}`);
  };
  function exportCsv() {
    const esc = (v: unknown) => {
      const s = v == null ? "" : String(v);
      return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };
    const csv = [report.columns.map((c) => esc(c.label)).join(","), ...report.rows.map((r) => report.columns.map((c) => esc(r[c.key])).join(","))].join("\n");
    const url = URL.createObjectURL(new Blob(["﻿" + csv], { type: "text/csv;charset=utf-8" }));
    const a = document.createElement("a");
    a.href = url;
    a.download = `${type}-report.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }
  const showResFilters = type === "reservations";
  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2 no-print">
        <div className="flex flex-wrap gap-1">
          {types.map((t) => (
            <button key={t} type="button" onClick={() => set("type", t)} className={cn("rounded-full border px-3 py-1.5 text-xs font-medium transition", type === t ? "border-primary bg-primary/10 text-primary" : "border-border text-fg-muted hover:border-border-strong")}>
              {LABELS[t] ?? t}
            </button>
          ))}
        </div>
        <div className="flex w-full flex-wrap items-center gap-2 sm:ml-auto sm:w-auto">
          {showResFilters || type === "commissions" || type === "workers" ? <FilterSelect value={filters.worker ?? ""} onChange={(v) => set("worker", v)} placeholder="All workers" options={workers.map((w) => ({ value: w.id, label: w.fullName }))} /> : null}
          {showResFilters ? <FilterSelect value={filters.source ?? ""} onChange={(v) => set("source", v)} placeholder="All sources" options={RESERVATION_SOURCES.map((s) => ({ value: s, label: RESERVATION_SOURCE_META[s].label }))} /> : null}
          {showResFilters ? <FilterSelect value={filters.status ?? ""} onChange={(v) => set("status", v)} placeholder="All statuses" options={RESERVATION_STATUSES.map((s) => ({ value: s, label: RESERVATION_STATUS_META[s].label }))} /> : null}
          <Button variant="secondary" size="sm" onClick={exportCsv}>
            <Download /> CSV
          </Button>
          <Button variant="secondary" size="sm" onClick={() => window.print()}>
            <Printer /> Print / PDF
          </Button>
        </div>
      </div>

      <div className="print-area">
        <div className="mb-3 hidden print:block">
          <h1 className="text-xl font-semibold">{businessName} · {report.title}</h1>
          <p className="text-sm text-fg-muted">{periodLabel}</p>
        </div>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4 lg:grid-cols-5">
          {report.summary.map((s) => (
            <div key={s.label} className="surface p-3">
              <p className="text-2xs font-semibold uppercase tracking-wider text-fg-muted">{s.label}</p>
              <p className="mt-1 text-lg font-semibold tabular">{s.money ? fmtMoney(Number(s.value), currency) : typeof s.value === "number" ? fmtNumber(s.value) : s.value}</p>
            </div>
          ))}
        </div>
        {report.chart && report.rows.length > 1 && report.rows.length <= 40 ? (
          <Card className="mt-4">
            <CardContent className="pt-5">
              <p className="mb-2 text-sm font-semibold">{report.chart.label}</p>
              <HBarChart data={report.rows.slice(0, 20).map((r) => ({ name: String(r[report.chart!.nameKey]).slice(0, 18), value: Number(r[report.chart!.key]) }))} money={report.chart.money} color={CHART_COLORS.primary} />
            </CardContent>
          </Card>
        ) : null}
        <Card className="mt-4 overflow-hidden">
          <div className="border-b border-border px-4 py-2.5 text-sm font-semibold">
            {report.title} <span className="font-normal text-fg-muted">· {periodLabel} · {report.rows.length} rows</span>
          </div>
          <div className="overflow-x-auto scrollbar-thin">
            <table className="w-full text-xs">
              <thead className="bg-surface-2/60 text-left text-2xs font-semibold uppercase tracking-wider text-fg-muted">
                <tr>
                  {report.columns.map((c) => (
                    <th key={c.key} className={cn("whitespace-nowrap px-3 py-2", c.align === "right" && "text-right")}>
                      {c.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {report.rows.length === 0 ? (
                  <tr>
                    <td colSpan={report.columns.length} className="px-3 py-10 text-center text-sm text-fg-muted">
                      No data for this period.
                    </td>
                  </tr>
                ) : (
                  report.rows.map((r, i) => (
                    <tr key={i} className="border-t border-border">
                      {report.columns.map((c) => (
                        <td key={c.key} className={cn("whitespace-nowrap px-3 py-1.5", c.align === "right" && "text-right tabular")}>
                          {c.money ? fmtMoney(Number(r[c.key]), currency) : typeof r[c.key] === "number" ? fmtNumber(r[c.key] as number, 1) : r[c.key]}
                        </td>
                      ))}
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </Card>
      </div>
      <style jsx global>{`
        @media print {
          aside, header, nav, .no-print { display: none !important; }
          main { padding: 0 !important; max-width: none !important; }
          .print-area { width: 100%; }
        }
      `}</style>
    </div>
  );
}
