import { useNavigate, useSearch } from '@tanstack/react-router'
import { useCallback, useState } from 'react'
import { UploadCloud, FileText, Loader2, FlaskConical } from 'lucide-react'
import { v4 as uuidv4 } from 'uuid'
import { Card, CardContent } from '@/components/ui/card'
import { parseBpmnXml, extractActivityElements, extractGatewayElements, BpmnParseError } from '@/domain/bpmn-parser'
import { processRepo, activityRepo, gatewayRepo } from '@/persistence/repositories'
import type { Process, Activity, GatewayConfig } from '@/domain/types'
import { bpmnTypeToGatewayType } from '@/domain/types'
import { useToast } from '@/components/ui/use-toast'
import { AppFooter } from '@/components/AppFooter'
import { AppHeader } from '@/components/AppHeader'

const SAMPLE_PROCESSES = [
  {
    id: 'simple-linear',
    fileName: 'simple-linear.bpmn',
    name: 'Proceso lineal simple',
    tags: ['5 tareas', 'Sin gateways'],
  },
  {
    id: 'medium-with-gateways',
    fileName: 'medium-with-gateways.bpmn',
    name: 'Aprobación de crédito',
    tags: ['XOR', 'Paralelo', '11 tareas'],
  },
  {
    id: 'complex-with-loop',
    fileName: 'complex-with-loop.bpmn',
    name: 'Control de calidad con revisión',
    tags: ['Loop', 'XOR', '9 tareas'],
  },
]

export function ImportPage() {
  const navigate = useNavigate()
  const { toast } = useToast()
  const [isDragging, setIsDragging] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)
  const [loadingSampleId, setLoadingSampleId] = useState<string | null>(null)

  // groupId viene de la URL cuando el usuario importa desde dentro de un grupo
  const search = useSearch({ from: '/import' })
  const targetGroupId = (search as { groupId?: string }).groupId ?? null

  const processFile = useCallback(async (file: File) => {
    if (!file.name.endsWith('.bpmn') && !file.name.endsWith('.xml')) {
      toast({
        title: 'Formato no válido',
        description: 'El archivo debe tener extensión .bpmn o .xml',
        variant: 'destructive',
      })
      return
    }

    setIsProcessing(true)

    try {
      const xml = await file.text()
      const graph = parseBpmnXml(xml)

      const processId = uuidv4()
      const now = Date.now()

      const process: Process = {
        id: processId,
        name: file.name.replace(/\.(bpmn|xml)$/, ''),
        clientName: '',
        bpmnXml: xml,
        currency: 'USD',
        overheadPercentage: 0.2,
        annualFrequency: 1000,
        analysisHorizonYears: 3,
        automationInvestment: 0,
        createdAt: now,
        updatedAt: now,
        groupId: targetGroupId,
        tags: [],
      }

      const activityElements = extractActivityElements(graph)
      const activities: Activity[] = activityElements.map((el) => ({
        id: uuidv4(),
        processId,
        bpmnElementId: el.bpmnElementId,
        name: el.name,
        type: el.type,
        directCostFixed: 0,
        executionTimeMinutes: 0,
        assignedResources: [],
        automatable: false,
        automatedCostFixed: 0,
        automatedTimeMinutes: 0,
        automatedAssignedResources: [],
      }))

      const gatewayElements = extractGatewayElements(graph)
      const gateways: GatewayConfig[] = gatewayElements.map((el) => {
        const gwType = bpmnTypeToGatewayType(el.gatewayType as any)
        const n = el.outgoing.length
        return {
          id: uuidv4(),
          processId,
          bpmnElementId: el.bpmnElementId,
          gatewayType: gwType,
          branches: el.outgoing.map((flowId) => ({
            flowId,
            targetElementId: graph.flows.get(flowId)?.targetRef ?? '',
            probability: gwType === 'parallel' ? 1.0 : parseFloat((1 / n).toFixed(4)),
          })),
        }
      })

      await Promise.all([
        processRepo.save(process),
        activityRepo.saveMany(activities),
        gatewayRepo.saveMany(gateways),
      ])

      toast({
        title: 'Proceso importado',
        description: `${activityElements.length} ${activityElements.length === 1 ? 'actividad' : 'actividades'} detectadas. Configurá los costos para simular.`,
      })

      navigate({ to: '/workspace/$processId', params: { processId } })
    } catch (err) {
      setIsProcessing(false)
      if (err instanceof BpmnParseError) {
        toast({
          title: 'BPMN 2.0 no válido',
          description: 'El archivo no pudo ser interpretado como un diagrama BPMN 2.0 estándar.',
          variant: 'destructive',
        })
      } else {
        toast({
          title: 'Error al procesar el archivo',
          description: 'Ocurrió un error inesperado. Verificá que el archivo no esté dañado.',
          variant: 'destructive',
        })
        console.error(err)
      }
    }
  }, [navigate, toast])

  const onDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    const file = e.dataTransfer.files[0]
    if (file) processFile(file)
  }, [processFile])

  const onFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) processFile(file)
  }, [processFile])

  async function handleSampleLoad(sample: typeof SAMPLE_PROCESSES[0]) {
    setLoadingSampleId(sample.id)
    try {
      const response = await fetch(`/sample-processes/${sample.fileName}`)
      if (!response.ok) throw new Error('No se pudo cargar el proceso de ejemplo')
      const text = await response.text()
      const file = new File([text], sample.fileName, { type: 'text/xml' })
      await processFile(file)
    } catch (err) {
      toast({
        title: 'Error al cargar el ejemplo',
        description: 'No se pudo descargar el proceso. Intentá de nuevo.',
        variant: 'destructive',
      })
      console.error(err)
    } finally {
      setLoadingSampleId(null)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex flex-col">
      <AppHeader />
      <div className="flex-1 flex flex-col items-center justify-center p-6">
      {/* Header */}
      <div className="text-center mb-10">
        <div className="inline-flex items-center gap-2 text-primary text-sm font-medium mb-4 bg-primary/10 px-3 py-1 rounded-full">
          <FlaskConical className="h-3.5 w-3.5" />
          Process Cost Platform · MVP Fase 0
        </div>
        <h1 className="text-4xl font-bold text-slate-900 mb-3">
          Cuantificá el costo operativo<br />de tus procesos
        </h1>
        <p className="text-lg text-slate-500 max-w-xl">
          Importá un archivo BPMN 2.0 y obtené un reporte visual de costos
          listo para presentar a tu cliente en minutos.
        </p>
      </div>

      {/* Drop zone */}
      <Card className="w-full max-w-lg shadow-lg">
        <CardContent className="p-0">
          <label
            htmlFor="bpmn-file-input"
            onDragOver={(e) => { e.preventDefault(); setIsDragging(true) }}
            onDragLeave={() => setIsDragging(false)}
            onDrop={onDrop}
            className={`
              flex flex-col items-center justify-center gap-4 p-12 rounded-xl cursor-pointer
              border-2 border-dashed transition-all duration-200
              ${isDragging
                ? 'border-primary bg-primary/5 scale-[1.01]'
                : 'border-slate-200 hover:border-primary/50 hover:bg-slate-50'
              }
            `}
          >
            {isProcessing ? (
              <>
                <Loader2 className="h-12 w-12 text-primary animate-spin" />
                <p className="text-slate-600 font-medium">Procesando el diagrama…</p>
              </>
            ) : (
              <>
                <div className={`p-4 rounded-full transition-colors ${isDragging ? 'bg-primary/10' : 'bg-slate-100'}`}>
                  <UploadCloud className={`h-10 w-10 transition-colors ${isDragging ? 'text-primary' : 'text-slate-400'}`} />
                </div>
                <div className="text-center">
                  <p className="text-slate-700 font-semibold text-lg">
                    Arrastrá tu archivo .bpmn aquí
                  </p>
                  <p className="text-slate-400 text-sm mt-1">
                    o hacé click para seleccionarlo desde tu computadora
                  </p>
                </div>
                <div className="flex items-center gap-2 text-xs text-slate-400">
                  <FileText className="h-3.5 w-3.5" />
                  BPMN 2.0 XML estándar (.bpmn, .xml)
                </div>
              </>
            )}
            <input
              id="bpmn-file-input"
              type="file"
              accept=".bpmn,.xml"
              className="hidden"
              onChange={onFileInput}
              disabled={isProcessing}
            />
          </label>
        </CardContent>
      </Card>

      {/* Procesos de ejemplo — visibles directamente */}
      <div className="mt-8 w-full max-w-lg">
        <p className="text-xs text-slate-400 uppercase tracking-wide font-medium text-center mb-3">
          O cargá un proceso de ejemplo con un click
        </p>
        <div className="grid grid-cols-3 gap-3">
          {SAMPLE_PROCESSES.map((sample) => {
            const isLoading = loadingSampleId === sample.id
            return (
              <button
                key={sample.id}
                onClick={() => handleSampleLoad(sample)}
                disabled={isProcessing || loadingSampleId !== null}
                className="flex flex-col items-start gap-2 p-3 rounded-xl border border-slate-200 bg-white hover:border-primary/40 hover:shadow-sm transition-all text-left disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <div className="flex items-center justify-between w-full">
                  <div className="p-1.5 bg-primary/10 rounded-lg">
                    {isLoading
                      ? <Loader2 className="h-3.5 w-3.5 text-primary animate-spin" />
                      : <FileText className="h-3.5 w-3.5 text-primary" />
                    }
                  </div>
                </div>
                <p className="text-xs font-semibold text-slate-700 leading-tight">{sample.name}</p>
                <div className="flex flex-wrap gap-1">
                  {sample.tags.map((tag) => (
                    <span key={tag} className="text-[10px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded-full">
                      {tag}
                    </span>
                  ))}
                </div>
              </button>
            )
          })}
        </div>
      </div>

      <p className="mt-8 text-xs text-slate-300">
        100% en tu navegador · Sin backend · Sin registro · Datos guardados localmente
      </p>

      <AppFooter />
      </div>
    </div>
  )
}
