import { useEffect, useState } from 'react'
import { useNavigate, useSearch, Link } from '@tanstack/react-router'
import { Users2, Search, Plus, Pencil, Trash2, ArrowLeft, CornerUpLeft, ChevronDown, ChevronRight } from 'lucide-react'
import { AppHeader } from '@/components/AppHeader'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table'
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
import { useAuth } from '@/auth/AuthContext'
import { supabaseResourceRepo, type ResourceWithCreator } from '@/persistence/supabase/resource-repo'
import { supabaseProcessRepo } from '@/persistence/supabase/process-repo'
import { formatCostPerHour } from '@/lib/format'
import { RESOURCE_TYPE_LABELS, RESOURCE_TYPE_STYLES } from './resource-types'
import { ResourceTypeAvatar } from './resource-display'
import { ResourceFormSheet } from './ResourceFormSheet'
import type { Resource, ResourceType } from '@/domain/types'

export function ResourceCatalogPage() {
  const { user } = useAuth()
  const navigate = useNavigate()
  const search_ = useSearch({ from: '/recursos' })
  const fromProcess = (search_ as { fromProcess?: string }).fromProcess
  const [fromProcessName, setFromProcessName] = useState<string | null>(null)
  const [resources, setResources] = useState<ResourceWithCreator[]>([])
  const [processCounts, setProcessCounts] = useState<Record<string, number>>({})
  const [expandedResourceId, setExpandedResourceId] = useState<string | null>(null)
  const [expandedProcesses, setExpandedProcesses] = useState<Record<string, { id: string; name: string }[]>>({})
  const [isLoading, setIsLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [typeFilter, setTypeFilter] = useState<ResourceType | 'all'>('all')
  const [sheetOpen, setSheetOpen] = useState(false)
  const [editing, setEditing] = useState<Resource | undefined>(undefined)
  const [deleteError, setDeleteError] = useState<string | null>(null)
  const [confirmingDeleteId, setConfirmingDeleteId] = useState<string | null>(null)

  useEffect(() => {
    if (!fromProcess) return
    supabaseProcessRepo.getById(fromProcess).then((p) => setFromProcessName(p?.name ?? null))
  }, [fromProcess])

  function backToProcess() {
    if (fromProcess) navigate({ to: '/workspace/$processId', params: { processId: fromProcess } })
  }

  async function load() {
    setIsLoading(true)
    try {
      const [data, counts] = await Promise.all([
        supabaseResourceRepo.getAllWithCreator(),
        supabaseResourceRepo.getProcessCountsPerResource(),
      ])
      setResources(data)
      setProcessCounts(counts)
    } finally {
      setIsLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  async function toggleExpanded(resourceId: string) {
    if (expandedResourceId === resourceId) {
      setExpandedResourceId(null)
      return
    }
    setExpandedResourceId(resourceId)
    if (!expandedProcesses[resourceId]) {
      const processes = await supabaseResourceRepo.getProcessesForResource(resourceId)
      setExpandedProcesses((prev) => ({ ...prev, [resourceId]: processes }))
    }
  }

  const filtered = resources.filter((r) => {
    const matchesName = r.name.toLowerCase().includes(search.toLowerCase())
    const matchesType = typeFilter === 'all' || r.type === typeFilter
    return matchesName && matchesType
  })

  function startCreate() {
    setEditing(undefined)
    setSheetOpen(true)
  }

  function startEdit(resource: Resource) {
    setEditing(resource)
    setSheetOpen(true)
  }

  async function handleSave(resource: Resource) {
    await supabaseResourceRepo.save(resource, user!.id)
    await load()
  }

  async function handleDelete(resourceId: string) {
    setDeleteError(null)
    try {
      await supabaseResourceRepo.delete(resourceId)
      setConfirmingDeleteId(null)
      await load()
    } catch (err) {
      setDeleteError(err instanceof Error ? err.message : 'No se pudo eliminar el recurso')
      setConfirmingDeleteId(null)
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <AppHeader />
      <div className="max-w-4xl mx-auto px-6 py-8">
        {/* Header */}
        <div className="flex items-start justify-between mb-6">
          <div>
            <h1 className="text-[18px] font-medium">Catálogo de recursos</h1>
            <div className="flex items-center gap-1.5 mt-0.5">
              <Users2 className="h-3.5 w-3.5 text-muted-foreground" />
              <p className="text-[12px] text-muted-foreground">
                Compartido con todo el equipo · {resources.length} recurso{resources.length !== 1 ? 's' : ''}
              </p>
            </div>
          </div>
          <Button onClick={startCreate} className="gap-2 text-white" style={{ background: '#F59845' }}>
            <Plus className="h-4 w-4" />
            Nuevo recurso
          </Button>
        </div>

        {fromProcess && (
          <div
            className="flex items-center justify-between gap-3 mb-4 px-4 py-3 rounded-lg"
            style={{ background: '#FEF3E7', borderLeft: '3px solid #F59845' }}
          >
            <div className="flex items-center gap-3">
              <Button variant="ghost" size="icon" className="h-7 w-7 -ml-1" onClick={backToProcess}>
                <ArrowLeft className="h-4 w-4" />
              </Button>
              <div>
                <p className="text-[13px] font-medium">
                  Estás viendo el catálogo desde el proceso {fromProcessName ? `"${fromProcessName}"` : ''}
                </p>
                <p className="text-[12px] text-muted-foreground">
                  Seleccioná un recurso y usalo en una actividad al volver al workspace.
                </p>
              </div>
            </div>
            <Button variant="outline" size="sm" className="gap-1.5 shrink-0" onClick={backToProcess}>
              <ArrowLeft className="h-3.5 w-3.5" />
              Volver al proceso
            </Button>
          </div>
        )}

        {deleteError && (
          <div className="mb-4 px-3 py-2 rounded-lg text-[12px] border border-destructive/30 bg-destructive/10 text-destructive">
            {deleteError}
          </div>
        )}

        {/* Toolbar */}
        <div className="flex items-center gap-2 mb-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Buscar recurso por nombre..."
              className="pl-9"
            />
          </div>
          <Select value={typeFilter} onValueChange={(v) => setTypeFilter(v as ResourceType | 'all')}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Todos los tipos</SelectItem>
              {(Object.entries(RESOURCE_TYPE_LABELS) as [ResourceType, string][]).map(([value, label]) => (
                <SelectItem key={value} value={value}>{label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Tabla */}
        {!isLoading && filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 gap-2">
            <p className="text-[13px] font-medium text-secondary-foreground">
              {resources.length === 0 ? 'Sin recursos en el catálogo' : 'Sin resultados para esa búsqueda'}
            </p>
            <p className="text-[13px] text-muted-foreground">
              {resources.length === 0 && 'Creá el primer recurso del equipo'}
            </p>
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Recurso</TableHead>
                <TableHead>Tipo</TableHead>
                <TableHead>Costo/h</TableHead>
                <TableHead>Creado por</TableHead>
                <TableHead>Procesos</TableHead>
                <TableHead className="text-right">Acciones</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((resource) => {
                const count = processCounts[resource.id] ?? 0
                const isExpanded = expandedResourceId === resource.id
                return (
                  <>
                    <TableRow key={resource.id}>
                      <TableCell>
                        <div className="flex items-center gap-2.5">
                          <ResourceTypeAvatar type={resource.type} size={28} />
                          <span className="text-[13px] font-medium">{resource.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="outline"
                          style={{
                            background: RESOURCE_TYPE_STYLES[resource.type].bg,
                            color: RESOURCE_TYPE_STYLES[resource.type].fg,
                            borderColor: 'transparent',
                          }}
                        >
                          {RESOURCE_TYPE_LABELS[resource.type]}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-mono text-[13px]">{formatCostPerHour(resource.costPerHour)}</TableCell>
                      <TableCell className="text-[13px] text-muted-foreground">{resource.creatorName}</TableCell>
                      <TableCell>
                        {count > 0 ? (
                          <button
                            type="button"
                            onClick={() => toggleExpanded(resource.id)}
                            className="inline-flex items-center gap-1 text-xs font-medium text-orange-600 bg-orange-50 hover:bg-orange-100 rounded-md px-2 py-0.5 transition-colors"
                          >
                            {isExpanded ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
                            {count} {count === 1 ? 'proceso' : 'procesos'}
                          </button>
                        ) : (
                          <span className="text-muted-foreground text-[13px]">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        {confirmingDeleteId === resource.id ? (
                          <div className="flex items-center justify-end gap-1.5">
                            <span className="text-[11px] text-muted-foreground">¿Eliminar?</span>
                            <Button size="sm" variant="destructive" className="h-7 text-[11px]" onClick={() => handleDelete(resource.id)}>
                              Sí
                            </Button>
                            <Button size="sm" variant="outline" className="h-7 text-[11px]" onClick={() => setConfirmingDeleteId(null)}>
                              No
                            </Button>
                          </div>
                        ) : (
                          <div className="flex items-center justify-end gap-1">
                            {fromProcess && (
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-foreground" onClick={backToProcess}>
                                    <CornerUpLeft className="h-3.5 w-3.5" />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top" className="max-w-48 text-xs">
                                  Volver al workspace para asignar este recurso a una actividad
                                </TooltipContent>
                              </Tooltip>
                            )}
                            <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-foreground" onClick={() => startEdit(resource)}>
                              <Pencil className="h-3.5 w-3.5" />
                            </Button>
                            <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-destructive" onClick={() => setConfirmingDeleteId(resource.id)}>
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        )}
                      </TableCell>
                    </TableRow>

                    {isExpanded && (
                      <TableRow key={`${resource.id}-processes`} className="bg-orange-50/40 hover:bg-orange-50/40">
                        <TableCell colSpan={6} className="px-4 pb-3 pt-1">
                          <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1.5">
                            Procesos que usan este recurso
                          </p>
                          {expandedProcesses[resource.id] ? (
                            <div className="flex flex-wrap gap-2">
                              {expandedProcesses[resource.id].map((p) => (
                                <Link
                                  key={p.id}
                                  to="/workspace/$processId"
                                  params={{ processId: p.id }}
                                  className="text-xs text-blue-600 hover:underline"
                                >
                                  {p.name}
                                </Link>
                              ))}
                              {expandedProcesses[resource.id].length === 0 && (
                                <span className="text-xs text-muted-foreground">Sin procesos encontrados</span>
                              )}
                            </div>
                          ) : (
                            <span className="text-xs text-muted-foreground">Cargando...</span>
                          )}
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                )
              })}
            </TableBody>
          </Table>
        )}
      </div>

      <ResourceFormSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        resource={editing}
        onSave={handleSave}
      />
    </div>
  )
}
