"use client"

import { useState, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet"
import { Download, Upload, Info, RefreshCw } 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
}

interface BulkUploadSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onUploadComplete?: () => void
}

export function BulkUploadSheet({
  open,
  onOpenChange,
  onUploadComplete,
}: BulkUploadSheetProps) {
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [history, setHistory] = useState<UploadHistoryEntry[]>([])
  const [dragOver, setDragOver] = useState(false)

  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 processFile = async (file: File) => {
    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`,
        )
        onUploadComplete?.()
      } else if (status === "Parcial") {
        toast.warning(
          `Carga parcial: ${data.success} de ${data.total} recursos creados, ${data.failed} con errores`,
        )
        onUploadComplete?.()
      } 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 handleFileSelected = async (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = e.target.files?.[0]
    if (!file) return
    e.target.value = ""
    await processFile(file)
  }

  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    const file = e.dataTransfer.files?.[0]
    if (!file) return
    await processFile(file)
  }

  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 (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        className="w-full sm:max-w-lg overflow-y-auto"
      >
        <SheetHeader>
          <SheetTitle className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Carga masiva de recursos
          </SheetTitle>
          <SheetDescription className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            Adjunte el archivo .XLSX con los campos requeridos completados
            previamente.
          </SheetDescription>
        </SheetHeader>

        <div className="flex flex-col gap-6 px-4 pb-4">
          {/* Drop zone */}
          <div
            className={`flex flex-col items-center justify-center gap-3 rounded-[var(--ds-radius-l)] border-2 border-dashed p-8 transition-colors ${
              dragOver
                ? "border-[var(--ds-brand-400)] bg-[var(--ds-brand-50)]"
                : "border-[var(--ds-neutral-300)] bg-[var(--ds-neutral-50)]"
            }`}
            onDragOver={(e) => {
              e.preventDefault()
              setDragOver(true)
            }}
            onDragLeave={() => setDragOver(false)}
            onDrop={handleDrop}
          >
            <Upload className="h-8 w-8 text-[var(--ds-text-neutral-lighter)]" />
            <p className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)] text-center">
              Elija un archivo o arrástrelo aquí
            </p>
            <p className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)] text-center">
              Adjunte el archivo .XLSX con los campos requeridos completados
              previamente.
            </p>
            <Button
              variant="outline"
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
            >
              <Upload className="mr-2 h-4 w-4" />
              {uploading ? "Subiendo..." : "Subir archivo"}
            </Button>
            <input
              ref={fileInputRef}
              type="file"
              accept=".xlsx,.xls,.csv"
              className="hidden"
              onChange={handleFileSelected}
            />
          </div>

          {/* Tips */}
          <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-4">
            <div className="flex items-center gap-2 mb-3">
              <Info className="h-4 w-4 text-[var(--ds-brand-400)]" />
              <h3 className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Consejos para completar la plantilla
              </h3>
            </div>
            <p className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)] mb-2">
              Debes completar los siguientes campos:
            </p>
            <ul className="space-y-2 ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Nombre:
                </strong>{" "}
                nombre identificatorio del recurso (ej: Sala Aconcagua, Box 3)
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Tipo de recurso:
                </strong>{" "}
                debe coincidir exactamente con un tipo de recurso existente
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Ubicación:
                </strong>{" "}
                ruta completa de la ubicación (ej: Argentina &gt; Buenos Aires
                &gt; Cowork Palermo)
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Capacidad:
                </strong>{" "}
                cantidad máxima de personas (número entero)
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Piso / Detalle:
                </strong>{" "}
                (opcional) información adicional de ubicación
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Amenidades:
                </strong>{" "}
                (opcional) separadas por coma (ej: TV, Pizarra, WiFi)
              </li>
              <li>
                <strong className="text-[var(--ds-text-neutral-default)]">
                  Activo:
                </strong>{" "}
                Sí o No
              </li>
            </ul>
          </div>

          {/* Download template */}
          <Button
            variant="outline"
            onClick={handleDownloadTemplate}
            className="w-full 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>

          {/* History */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Historial
              </h3>
              <button
                type="button"
                className="flex items-center gap-1 ds-type-global-xxs text-[var(--ds-brand-400)] hover:text-[var(--ds-brand-500)]"
                onClick={() => {
                  /* refresh */
                }}
              >
                Actualizar <RefreshCw className="h-3 w-3" />
              </button>
            </div>
            <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white">
              <Table>
                <TableHeader>
                  <TableRow className="border-[var(--ds-neutral-200)]">
                    <TableHead className="ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                      Archivo
                    </TableHead>
                    <TableHead className="ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                      Fecha
                    </TableHead>
                    <TableHead className="ds-type-global-xxs 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-xxs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                        {entry.fileName}
                      </TableCell>
                      <TableCell className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                        {entry.date} {entry.time}
                      </TableCell>
                      <TableCell>
                        <Badge className={statusBadgeClass[entry.status]}>
                          {entry.status}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                  {history.length === 0 && (
                    <TableRow>
                      <TableCell
                        colSpan={3}
                        className="py-8 text-center ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
                      >
                        No hay cargas registradas
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        </div>
      </SheetContent>
    </Sheet>
  )
}
