import { useState } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { Plus, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useProcessStore } from '@/store/process-store'
import { useAuth } from '@/auth/AuthContext'
import { formatCostPerHour } from '@/lib/format'
import { RESOURCE_TYPE_LABELS } from '@/features/resources/resource-types'
import { ResourceTypeAvatar } from '@/features/resources/resource-display'
import { ResourceFormSheet } from '@/features/resources/ResourceFormSheet'
import type { Resource } from '@/domain/types'

export function ResourcesPanel() {
  const { currentProcess, activities, resources, addResource } = useProcessStore()
  const { user } = useAuth()
  const navigate = useNavigate()
  const [sheetOpen, setSheetOpen] = useState(false)

  const usedResourceIds = new Set(
    activities.flatMap((a) => a.assignedResources ?? []).map((ar) => ar.resourceId)
  )
  const usedResources = resources.filter((r) => usedResourceIds.has(r.id))
  const usageCount = (resourceId: string) =>
    activities.filter((a) => (a.assignedResources ?? []).some((ar) => ar.resourceId === resourceId)).length

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

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between p-4 pb-3 border-b border-slate-100">
        <p className="text-xs font-medium text-slate-700">Recursos</p>
        <Button
          size="sm"
          onClick={() => setSheetOpen(true)}
          className="h-7 text-xs gap-1 text-white"
          style={{ background: '#F59845' }}
        >
          <Plus className="h-3.5 w-3.5" />
          Nuevo
        </Button>
      </div>

      {/* Cuerpo */}
      <ScrollArea className="flex-1">
        <div className="p-4 space-y-3">
          <p className="text-xs font-medium text-slate-500">
            Usados en este proceso <span className="text-slate-400">({usedResources.length})</span>
          </p>

          {usedResources.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-xs text-slate-400">Ningún recurso asignado a actividades aún</p>
            </div>
          ) : (
            <div className="space-y-2">
              {usedResources.map((resource) => (
                <div
                  key={resource.id}
                  className="flex items-center gap-2.5 p-3 rounded-lg border border-slate-100 bg-white"
                >
                  <ResourceTypeAvatar type={resource.type} size={32} />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-xs font-medium text-slate-800 truncate">{resource.name}</p>
                      <p className="text-xs text-slate-500 font-mono shrink-0">{formatCostPerHour(resource.costPerHour)}/h</p>
                    </div>
                    <p className="text-[11px] text-slate-400 mt-0.5">
                      {RESOURCE_TYPE_LABELS[resource.type]} · {usageCount(resource.id)} actividad{usageCount(resource.id) !== 1 ? 'es' : ''}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </ScrollArea>

      {/* Footer */}
      <div className="p-4 pt-3 border-t border-slate-100 space-y-2">
        <p className="text-[11px] text-slate-400 text-center">Recursos del catálogo global del equipo</p>
        <Button
          variant="outline"
          className="w-full h-8 text-xs gap-1.5"
          onClick={() => navigate({
            to: '/recursos',
            search: currentProcess ? { fromProcess: currentProcess.id } : undefined,
          })}
        >
          <ExternalLink className="h-3.5 w-3.5" />
          Ver catálogo completo
        </Button>
      </div>

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