import { useState, useRef } from 'react'
import { Upload, FileSpreadsheet, CheckCircle, AlertCircle, Loader2, X } from 'lucide-react'
import api from '../services/api'

interface ImportResult {
  sucesso: boolean
  registros_importados?: number
  erros?: string[]
  mensagem?: string
}

export default function Importacao() {
  const [tipo, setTipo] = useState('orcamento')
  const [file, setFile] = useState<File | null>(null)
  const [dragging, setDragging] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [result, setResult] = useState<ImportResult | null>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setDragging(false)
    const f = e.dataTransfer.files[0]
    if (f) setFile(f)
  }

  const handleUpload = async () => {
    if (!file) return
    setUploading(true)
    setResult(null)
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('tipo', tipo)
      const { data } = await api.post('/import/excel', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      setResult(data)
    } catch (err: any) {
      setResult({ sucesso: false, mensagem: err.response?.data?.error || 'Erro ao importar arquivo.' })
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold text-text flex items-center gap-2">
          <Upload className="w-8 h-8 text-primary" /> Importação de Dados
        </h1>
        <p className="text-gray mt-1">Importe planilhas Excel para atualizar orçamentos ou demandas.</p>
      </div>

      <div className="card max-w-2xl mx-auto space-y-6">
        {/* Tipo selector */}
        <div>
          <label className="block text-sm font-medium text-text mb-2">Tipo de importação</label>
          <select value={tipo} onChange={e => setTipo(e.target.value)} className="input-field">
            <option value="orcamento">Orçamento</option>
            <option value="demandas">Demandas</option>
          </select>
        </div>

        {/* Drop zone */}
        <div
          onDragOver={e => { e.preventDefault(); setDragging(true) }}
          onDragLeave={() => setDragging(false)}
          onDrop={handleDrop}
          onClick={() => inputRef.current?.click()}
          className={`border-2 border-dashed rounded-2xl p-12 text-center cursor-pointer transition-all ${
            dragging ? 'border-primary bg-primary/5' : 'border-gray-300 hover:border-primary/50'
          }`}
        >
          <input
            ref={inputRef}
            type="file"
            accept=".xlsx,.xls,.csv"
            className="hidden"
            onChange={e => { if (e.target.files?.[0]) setFile(e.target.files[0]) }}
          />
          <FileSpreadsheet className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          {file ? (
            <div className="flex items-center justify-center gap-2">
              <span className="font-medium text-text">{file.name}</span>
              <button onClick={e => { e.stopPropagation(); setFile(null) }} className="p-1 rounded-full hover:bg-gray-100">
                <X className="w-4 h-4 text-gray" />
              </button>
            </div>
          ) : (
            <>
              <p className="font-medium text-text">Arraste o arquivo aqui ou clique para selecionar</p>
              <p className="text-sm text-gray mt-1">Formatos aceitos: .xlsx, .xls, .csv</p>
            </>
          )}
        </div>

        {/* Upload button */}
        <button
          onClick={handleUpload}
          disabled={!file || uploading}
          className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-50"
        >
          {uploading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Upload className="w-5 h-5" />}
          {uploading ? 'Importando...' : 'Importar'}
        </button>

        {/* Result */}
        {result && (
          <div className={`p-4 rounded-xl ${result.sucesso ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
            <div className="flex items-center gap-2 mb-2">
              {result.sucesso ? <CheckCircle className="w-5 h-5 text-green-500" /> : <AlertCircle className="w-5 h-5 text-red-500" />}
              <span className="font-medium">{result.sucesso ? 'Importação concluída!' : 'Erro na importação'}</span>
            </div>
            {result.registros_importados !== undefined && (
              <p className="text-sm text-gray">{result.registros_importados} registros importados com sucesso.</p>
            )}
            {result.mensagem && <p className="text-sm text-gray">{result.mensagem}</p>}
            {result.erros && result.erros.length > 0 && (
              <ul className="mt-2 space-y-1">
                {result.erros.map((e, i) => <li key={i} className="text-sm text-red-600">• {e}</li>)}
              </ul>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
