"use client";

import {
  DashboardPageIntro,
  DashboardSection,
} from "@/components/dashboard-page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useToast } from "@/hooks/use-toast";
import { catalogosApi } from "@/lib/api";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  CheckCircle2,
  Download,
  FileSpreadsheet,
  Loader2,
  Upload,
} from "lucide-react";
import { useState } from "react";

type ImportResult = {
  totalRows: number;
  processedRows: number;
  skippedRows: number;
  created: Record<string, number>;
  reactivated: Record<string, number>;
  existing: Record<string, number>;
  errors: Array<{ row: number; message: string }>;
};

function sumValues(values?: Record<string, number>) {
  return Object.values(values || {}).reduce(
    (sum, value) => sum + Number(value || 0),
    0,
  );
}

export default function CargasMasivasPage() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [vehicularFile, setVehicularFile] = useState<File | null>(null);

  const downloadTemplate = useMutation({
    mutationFn: catalogosApi.downloadFichaVehicularTemplate,
    onError: (error: any) => {
      toast({
        variant: "destructive",
        title: "Error",
        description:
          error?.message || "No se pudo descargar la plantilla vehicular.",
      });
    },
  });

  const importVehicular = useMutation({
    mutationFn: (file: File) => catalogosApi.importVehicularExcel(file),
    onSuccess: (result: ImportResult) => {
      queryClient.invalidateQueries({ queryKey: ["catalogos"] });
      queryClient.invalidateQueries({ queryKey: ["catalogos-vehiculares"] });
      setVehicularFile(null);
      toast({
        title: "Carga masiva procesada",
        description: `${result.processedRows || 0} filas aplicadas. ${sumValues(result.created)} creados, ${sumValues(result.reactivated)} reactivados.`,
      });
    },
    onError: (error: any) => {
      toast({
        variant: "destructive",
        title: "Error",
        description: error?.message || "No se pudo procesar el Excel.",
      });
    },
  });

  const result = importVehicular.data as ImportResult | undefined;

  return (
    <main className="mx-auto flex max-w-6xl flex-col gap-6 p-4 md:p-6">
      <DashboardPageIntro
        title="Cargas masivas"
        description="Plantillas controladas para crear registros en lote sin escribirlos uno por uno."
        icon={FileSpreadsheet}
        tone="slate"
        badge="Plantillas"
        stats={[
          {
            label: "Disponibles",
            value: "1",
            hint: "Ficha vehicular",
            icon: FileSpreadsheet,
          },
          {
            label: "Formato",
            value: ".xlsx",
            hint: "Encabezados validados",
            icon: CheckCircle2,
          },
        ]}
      />

      <DashboardSection
        title="Ficha vehicular"
        description="Carga tipos de vehículo, marcas y líneas desde una plantilla oficial. Serie motor y C.C. son opcionales si vienen en el archivo."
      >
        <div className="grid gap-4 xl:grid-cols-[minmax(0,1fr),360px]">
          <div className="rounded-xl border border-border bg-muted p-4 md:p-5">
            <div className="flex flex-col gap-4 md:flex-row md:items-start">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border border-border bg-surface text-foreground">
                <FileSpreadsheet className="h-5 w-5" />
              </span>
              <div className="min-w-0 flex-1">
                <h3 className="text-lg font-bold text-foreground">
                  Plantilla vehicular
                </h3>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">
                  Descarga la plantilla, llena las columnas TIPO, MARCA y LINEA,
                  y luego sube el mismo archivo en formato .xlsx.
                </p>

                <div className="mt-4 rounded-xl border border-border bg-surface p-3 text-sm text-muted-foreground">
                  <p className="font-semibold text-foreground">
                    Archivo seleccionado
                  </p>
                  <p className="mt-1 truncate">
                    {vehicularFile?.name || "Ningun archivo seleccionado"}
                  </p>
                </div>
              </div>
            </div>

            {result ? (
              <div className="mt-4 grid gap-3 md:grid-cols-4">
                <div className="rounded-xl border border-border bg-surface p-3">
                  <p className="text-xs font-semibold uppercase tracking-wider text-subtle-foreground">
                    Filas
                  </p>
                  <p className="mt-2 text-2xl font-bold text-foreground">
                    {result.processedRows}/{result.totalRows}
                  </p>
                </div>
                <div className="rounded-xl border border-success/30 bg-success-soft p-3">
                  <p className="text-xs font-semibold uppercase tracking-wider text-success">
                    Creados
                  </p>
                  <p className="mt-2 text-2xl font-bold text-success">
                    {sumValues(result.created)}
                  </p>
                </div>
                <div className="rounded-xl border border-primary/30 bg-primary-soft p-3">
                  <p className="text-xs font-semibold uppercase tracking-wider text-primary">
                    Reactivados
                  </p>
                  <p className="mt-2 text-2xl font-bold text-primary">
                    {sumValues(result.reactivated)}
                  </p>
                </div>
                <div className="rounded-xl border border-warning/30 bg-warning-soft p-3">
                  <p className="text-xs font-semibold uppercase tracking-wider text-warning">
                    Errores
                  </p>
                  <p className="mt-2 text-2xl font-bold text-warning">
                    {result.errors?.length || 0}
                  </p>
                </div>
              </div>
            ) : null}

            {result?.errors?.length ? (
              <div className="mt-4 overflow-hidden rounded-xl border border-warning/30">
                <div className="flex items-center gap-2 bg-warning-soft px-4 py-3 text-sm font-semibold text-warning">
                  <AlertTriangle className="h-4 w-4" />
                  Filas que no se aplicaron
                </div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-20">Fila</TableHead>
                      <TableHead>Detalle</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {result.errors.slice(0, 8).map((item) => (
                      <TableRow key={`${item.row}-${item.message}`}>
                        <TableCell>
                          <Badge variant="warning">Fila {item.row}</Badge>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{item.message}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : null}
          </div>

          <div className="rounded-xl border border-border bg-surface p-4 shadow-sm md:p-5">
            <div className="space-y-3">
              <Button
                variant="outline"
                className="h-12 w-full"
                disabled={downloadTemplate.isPending}
                onClick={() => downloadTemplate.mutate()}
              >
                {downloadTemplate.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Download className="mr-2 h-4 w-4" />
                )}
                Descargar plantilla
              </Button>

              <label className="inline-flex h-12 w-full cursor-pointer items-center justify-center gap-2 rounded-md border border-border bg-surface px-4 text-sm font-semibold text-foreground transition-colors duration-150 ease-out [@media(hover:hover)]:hover:bg-muted active:scale-[0.98]">
                <Upload className="h-4 w-4" />
                Elegir archivo
                <input
                  type="file"
                  accept=".xlsx"
                  className="sr-only"
                  onChange={(event) =>
                    setVehicularFile(event.target.files?.[0] || null)
                  }
                />
              </label>

              <Button
                className="h-12 w-full"
                disabled={!vehicularFile || importVehicular.isPending}
                onClick={() =>
                  vehicularFile && importVehicular.mutate(vehicularFile)
                }
              >
                {importVehicular.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Upload className="mr-2 h-4 w-4" />
                )}
                Importar ficha vehicular
              </Button>
            </div>
          </div>
        </div>
      </DashboardSection>
    </main>
  );
}
