import Link from "next/link";
import { notFound } from "next/navigation";
import { BarChart3, FileSpreadsheet, FileText, Filter } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ReportesDashboard } from "@/components/reportes/reportes-dashboard";
import { getReportesData } from "@/server/queries/reportes";
import { requireUser } from "@/lib/session";
import { can } from "@/lib/permissions";
import {
  buildReportQueryString,
  describeReportFilters,
  estadoFichaReportOptions,
  manzanaReportOptions,
  parseReportFilters,
  situacionLoteReportOptions,
  tramoRshReportOptions,
} from "@/lib/reportes";

export const dynamic = "force-dynamic";

export default async function ReportesPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const user = await requireUser();
  if (!can(user.role, "dashboard:read")) notFound();

  const params = await searchParams;
  const filters = parseReportFilters(params);
  const report = await getReportesData(filters);
  const queryString = buildReportQueryString(filters);
  const canExport = can(user.role, "reporte:export");
  const activeFilters = describeReportFilters(filters);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div className="space-y-2">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-3 py-1 text-xs font-medium text-muted-foreground shadow-sm">
            <BarChart3 className="h-3.5 w-3.5" />
            Panel territorial
          </div>
          <h2 className="text-2xl font-semibold tracking-tight">Reportes</h2>
          <p className="max-w-3xl text-sm text-muted-foreground">
            Reportes territoriales, sociales y administrativos para priorización y apoyo a la toma de decisiones.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {canExport ? (
            <>
              <Button asChild variant="outline" className="gap-2">
                <Link href={`/api/reportes/export/excel${queryString}`}>
                  <FileSpreadsheet className="h-4 w-4" />
                  Exportar Excel
                </Link>
              </Button>
              <Button asChild variant="outline" className="gap-2">
                <Link href={`/api/reportes/export/pdf${queryString}`}>
                  <FileText className="h-4 w-4" />
                  Exportar PDF
                </Link>
              </Button>
            </>
          ) : (
            <>
              <Button variant="outline" className="gap-2" disabled>
                <FileSpreadsheet className="h-4 w-4" />
                Exportar Excel
              </Button>
              <Button variant="outline" className="gap-2" disabled>
                <FileText className="h-4 w-4" />
                Exportar PDF
              </Button>
            </>
          )}
        </div>
      </div>

      <Card className="border-border shadow-sm">
        <CardContent className="p-4">
          <form className="grid gap-3 md:grid-cols-2 xl:grid-cols-6">
            <div className="space-y-2 xl:col-span-2">
              <Label htmlFor="reportes-q">Buscar por nombre / RUT / dirección</Label>
              <div className="relative">
                <Filter className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input id="reportes-q" name="q" defaultValue={filters.q ?? ""} placeholder="Buscar..." className="pl-9" />
              </div>
            </div>

            <SelectFilter label="Manzana" name="manzana" value={filters.manzana ?? ""} options={manzanaReportOptions} />
            <SelectFilter label="Estado ficha" name="estadoFicha" value={filters.estadoFicha ?? ""} options={estadoFichaReportOptions} />
            <SelectFilter label="Situación lote" name="situacionLote" value={filters.situacionLote ?? ""} options={situacionLoteReportOptions} />
            <SelectFilter label="Tramo RSH" name="tramoRsh" value={filters.tramoRsh ?? ""} options={tramoRshReportOptions} />

            <div className="space-y-2">
              <Label htmlFor="reportes-fecha-desde">Fecha creación desde</Label>
              <Input id="reportes-fecha-desde" type="date" name="fechaDesde" defaultValue={filters.fechaDesde ?? ""} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="reportes-fecha-hasta">Fecha creación hasta</Label>
              <Input id="reportes-fecha-hasta" type="date" name="fechaHasta" defaultValue={filters.fechaHasta ?? ""} />
            </div>

            <div className="flex flex-wrap items-end gap-2 xl:col-span-6">
              <Button type="submit" className="gap-2">
                Aplicar filtros
              </Button>
              <Button asChild variant="outline">
                <Link href="/reportes">Limpiar</Link>
              </Button>
              {activeFilters.length > 0 ? (
                <p className="text-sm text-muted-foreground">
                  {activeFilters.length} filtro{activeFilters.length === 1 ? "" : "s"} activos
                </p>
              ) : null}
            </div>
          </form>
        </CardContent>
      </Card>

      <ReportesDashboard data={report} />
    </div>
  );
}

function SelectFilter({
  label,
  name,
  value,
  options,
}: {
  label: string;
  name: string;
  value: string;
  options: ReadonlyArray<{ value: string; label: string }>;
}) {
  const id = `reportes-${name}`;

  return (
    <div className="space-y-2">
      <Label htmlFor={id}>{label}</Label>
      <select
        id={id}
        name={name}
        defaultValue={value}
        className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground shadow-sm focus:outline-none focus:ring-2 focus:ring-ring"
      >
        <option value="">Seleccione</option>
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </div>
  );
}
