import { useState } from 'react'
import { ArrowLeft, FileText, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface SampleProcess {
  id: string
  fileName: string
  name: string
  description: string
  tags: string[]
}

const SAMPLE_PROCESSES: SampleProcess[] = [
  {
    id: 'simple-linear',
    fileName: 'simple-linear.bpmn',
    name: 'Proceso Lineal Simple',
    description: '5 tareas en secuencia sin gateways. Ideal para validar el flujo básico de importación y costeo.',
    tags: ['Lineal', '5 tareas', 'Sin gateways'],
  },
  {
    id: 'medium-with-gateways',
    fileName: 'medium-with-gateways.bpmn',
    name: 'Aprobación de Crédito',
    description: '12 tareas con un gateway exclusivo (XOR) y un gateway paralelo (AND). Caso de negocio real.',
    tags: ['XOR', 'Paralelo', '12 tareas'],
  },
  {
    id: 'complex-with-loop',
    fileName: 'complex-with-loop.bpmn',
    name: 'Control de Calidad con Revisión',
    description: 'Proceso con un loop de correcciones que vuelve a la inspección. Valida la detección de ciclos.',
    tags: ['Loop', 'XOR', '9 tareas'],
  },
]

interface SampleProcessLoaderProps {
  onBack: () => void
  onLoad: (file: File) => void
}

export function SampleProcessLoader({ onBack, onLoad }: SampleProcessLoaderProps) {
  const [loadingId, setLoadingId] = useState<string | null>(null)

  async function handleSelect(sample: SampleProcess) {
    setLoadingId(sample.id)
    try {
      const response = await fetch(`/sample-processes/${sample.fileName}`)
      if (!response.ok) throw new Error('No se pudo cargar el archivo de ejemplo')
      const text = await response.text()
      const file = new File([text], sample.fileName, { type: 'text/xml' })
      onLoad(file)
    } catch (err) {
      console.error('Error cargando proceso de ejemplo:', err)
      setLoadingId(null)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex flex-col items-center justify-center p-6">
      <div className="w-full max-w-2xl">
        <Button variant="ghost" size="sm" onClick={onBack} className="mb-6 text-slate-500">
          <ArrowLeft className="h-4 w-4 mr-1.5" />
          Volver
        </Button>

        <div className="mb-8">
          <h2 className="text-2xl font-bold text-slate-900 mb-1">Procesos de ejemplo</h2>
          <p className="text-slate-500">Seleccioná un proceso para comenzar la demo sin necesitar un archivo propio.</p>
        </div>

        <div className="flex flex-col gap-4">
          {SAMPLE_PROCESSES.map((sample) => (
            <Card
              key={sample.id}
              className="cursor-pointer hover:shadow-md transition-all border-slate-200 hover:border-primary/30"
              onClick={() => handleSelect(sample)}
            >
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-primary/10 rounded-lg">
                      <FileText className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-base">{sample.name}</CardTitle>
                      <CardDescription className="text-xs mt-0.5">{sample.fileName}</CardDescription>
                    </div>
                  </div>
                  {loadingId === sample.id ? (
                    <Loader2 className="h-5 w-5 text-primary animate-spin mt-1" />
                  ) : (
                    <Button size="sm" variant="outline" className="shrink-0">
                      Cargar
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="pt-0">
                <p className="text-sm text-slate-600 mb-3">{sample.description}</p>
                <div className="flex gap-2 flex-wrap">
                  {sample.tags.map((tag) => (
                    <span
                      key={tag}
                      className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    </div>
  )
}
