"use client"

import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { X, Download, Plus } from "lucide-react"
import { toast } from "sonner"

type UploadStatus = "Exitoso" | "Parcial" | "Error"

interface UploadHistoryEntry {
  id: string
  fileName: string
  date: string
  time: string
  status: UploadStatus
  total: number
  success: number
  failed: number
}

export default function BulkResourceUploadPage() {
  const router = useRouter()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [history, setHistory] = useState<UploadHistoryEntry[]>([])

  const handleDownloadTemplate = async () => {
    try {
      const res = await fetch("/api/resources/bulk/template")
      if (!res.ok) {
        toast.error("Error al descargar la planilla")
        return
      }
      const blob = await res.blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = "plantilla_recursos.xlsx"
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    } catch {
      toast.error("Error al descargar la planilla")
    }
  }

  const handleFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // Reset the input so the same file can be re-selected
    e.target.value = ""

    setUploading(true)
    const formData = new FormData()
    formData.append("file", file)

    try {
      const res = await fetch("/api/resources/bulk/upload", {
        method: "POST",
        body: formData,
      })
      const data = await res.json()

      const now = new Date()
      const date = now.toLocaleDateString("es-AR", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      })
      const time = now.toLocaleTimeString("es-AR", {
        hour: "2-digit",
        minute: "2-digit",
      })

      let status: UploadStatus
      if (!res.ok || data.success === 0) {
        status = "Error"
      } else if (data.failed > 0) {
        status = "Parcial"
      } else {
        status = "Exitoso"
      }

      const entry: UploadHistoryEntry = {
        id: crypto.randomUUID(),
        fileName: file.name,
        date,
        time,
        status,
        total: data.total ?? 0,
        success: data.success ?? 0,
        failed: data.failed ?? 0,
      }

      setHistory((prev) => [entry, ...prev])

      if (status === "Exitoso") {
        toast.success(
          `Carga exitosa: ${data.success} de ${data.total} recursos creados`,
        )
      } else if (status === "Parcial") {
        toast.warning(
          `Carga parcial: ${data.success} de ${data.total} recursos creados, ${data.failed} con errores`,
        )
      } else {
        const errorMsg =
          data.errors?.[0]?.message ?? "Error al procesar el archivo"
        toast.error(errorMsg)
      }
    } catch {
      toast.error("Error de red al subir el archivo")
    } finally {
      setUploading(false)
    }
  }

  const statusBadgeClass: Record<UploadStatus, string> = {
    Exitoso:
      "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-success-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-success-700)]",
    Parcial:
      "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-warning-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-warning-700)]",
    Error:
      "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-error-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-error-700)]",
  }

  return (
    <div className="space-y-[var(--ds-space-4x)]">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Carga masiva: Recursos
        </h1>
        <button
          type="button"
          onClick={() => router.push("/admin/resources")}
          className="flex h-9 w-9 items-center justify-center rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)] hover:text-[var(--ds-text-neutral-default)]"
          aria-label="Cerrar"
        >
          <X className="h-5 w-5" />
        </button>
      </div>

      {/* Section header + actions */}
      <div className="flex items-center justify-between">
        <h2 className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Historial
        </h2>
        <div className="flex items-center gap-[var(--ds-space-15x)]">
          <Button
            variant="outline"
            onClick={handleDownloadTemplate}
            className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
          >
            <Download className="mr-2 h-4 w-4" />
            Descargar planilla
          </Button>
          <Button
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading}
            className="rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] ds-type-global-xs ds-type-semibold text-white hover:bg-[var(--ds-brand-500)]"
          >
            <Plus className="mr-2 h-4 w-4" />
            {uploading ? "Subiendo..." : "Nueva carga masiva"}
          </Button>
          <input
            ref={fileInputRef}
            type="file"
            accept=".xlsx,.xls,.csv"
            className="hidden"
            onChange={handleFileSelected}
          />
        </div>
      </div>

      {/* History table */}
      <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white shadow-[var(--ds-shadow-4dp)]">
        <Table>
          <TableHeader>
            <TableRow className="border-[var(--ds-neutral-200)]">
              <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                Nombre del archivo
              </TableHead>
              <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                Fecha
              </TableHead>
              <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                Hora
              </TableHead>
              <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                Estado
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {history.map((entry) => (
              <TableRow
                key={entry.id}
                className="border-[var(--ds-neutral-200)] hover:bg-[var(--ds-neutral-100)]"
              >
                <TableCell className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  {entry.fileName}
                </TableCell>
                <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                  {entry.date}
                </TableCell>
                <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                  {entry.time}
                </TableCell>
                <TableCell>
                  <Badge className={statusBadgeClass[entry.status]}>
                    {entry.status}
                  </Badge>
                </TableCell>
              </TableRow>
            ))}
            {history.length === 0 && (
              <TableRow>
                <TableCell
                  colSpan={4}
                  className="py-12 text-center ds-type-global-xs text-[var(--ds-text-neutral-lighter)]"
                >
                  No hay cargas registradas
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}
