import React, { useState } from 'react';
import { FileText, Folder, Activity, ChevronRight, CheckCircle2, AlertCircle, Search } from 'lucide-react';
import { useGrOps } from '../hooks/useGrOps';
import { toast } from 'sonner';

const GrFiscalView = () => {
  const [selectedFolder, setSelectedFolder] = useState(null);
  const [placa, setPlaca] = useState("");
  const [option, setOption] = useState("1");
  const [logs, setLogs] = useState([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);

  const options = [
    { id: "1", label: "Nova Rio (ASVD)", color: "bg-emerald-500" },
    { id: "2", label: "JPA (CDI)", color: "bg-emerald-600" },
    { id: "3", label: "Piraí (CDI)", color: "bg-orange-500" }
  ];

  const handleRunAnalysis = async () => {
    if (!placa) {
      toast.error("Informe a placa do veículo");
      return;
    }
    
    setIsAnalyzing(true);
    setLogs(prev => [...prev, `[SYSTEM] Iniciando análise fiscal para ${placa.toUpperCase()}...`]);
    setLogs(prev => [...prev, `[CONFIG] Regra de negócio: ${options.find(o => o.id === option)?.label}`]);

    // Simulated logic
    setTimeout(() => {
        setLogs(prev => [...prev, "[IO] Lendo arquivos XML da pasta temporária..."]);
    }, 1000);

    setTimeout(() => {
        setLogs(prev => [...prev, "[PROCESS] Validando NFe com regras de destino..."]);
    }, 2500);

    setTimeout(() => {
        setIsAnalyzing(false);
        setLogs(prev => [...prev, "[SUCCESS] Análise concluída. Relatório gerado com sucesso!"]);
        toast.success("Análise Fiscal concluída!");
    }, 4500);
  };

  return (
    <div className="flex flex-col gap-8 p-6 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="space-y-4">
        <h1 className="text-4xl md:text-6xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
          Suporte <span className="text-[var(--gr-primary)]">Fiscal</span>
        </h1>
        <p className="text-slate-400 dark:text-slate-500 text-base md:text-lg font-medium italic opacity-80">
          Validação automatizada de NFe e regras de negócio logísticas (ASVD/CDI)
        </p>
      </header>

      <div className="max-w-4xl mx-auto w-full">
        <div className="bg-white dark:bg-[#1b1b1b] p-8 md:p-12 rounded-[40px] border border-slate-200 dark:border-white/5 shadow-sm space-y-10">
          <div className="grid md:grid-cols-2 gap-8">
            <div className="space-y-4">
              <label className="text-[10px] font-bold text-slate-400 uppercase tracking-widest ml-1">Regra de Negócio / Unidade</label>
              <div className="grid grid-cols-1 gap-3">
                {options.map((opt) => (
                  <button
                    key={opt.id}
                    onClick={() => setOption(opt.id)}
                    className={`flex items-center justify-between p-4 rounded-2xl border-2 transition-all ${
                      option === opt.id 
                        ? 'border-[var(--gr-primary)] bg-[var(--gr-primary)]/5 text-slate-900 dark:text-white' 
                        : 'border-slate-100 dark:border-white/5 text-slate-500 hover:border-slate-200'
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      <div className={`w-3 h-3 rounded-full ${opt.color}`} />
                      <span className="font-bold text-sm tracking-tight">{opt.label}</span>
                    </div>
                    {option === opt.id && <CheckCircle2 size={18} className="text-[var(--gr-primary)]" />}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-6 flex flex-col justify-between">
              <div className="space-y-4">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-widest ml-1">Identificação do Veículo</label>
                <div className="relative group">
                  <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-colors" size={20} />
                  <input 
                    type="text" 
                    value={placa}
                    onChange={(e) => setPlaca(e.target.value.toUpperCase())}
                    className="w-full pl-12 pr-4 py-4 bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-[20px] text-sm focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 focus:border-[var(--gr-primary)] transition-all font-bold"
                    placeholder="ABC-1234"
                  />
                </div>
              </div>

              <button
                onClick={handleRunAnalysis}
                disabled={isAnalyzing}
                className="w-full flex items-center justify-center gap-3 px-8 py-6 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-[24px] font-bold text-xs uppercase tracking-[0.2em] transition-all shadow-xl shadow-[var(--gr-primary)]/20 hover:scale-[1.02] active:scale-95 disabled:opacity-50"
              >
                {isAnalyzing ? (
                  <Activity className="animate-spin" size={20} />
                ) : (
                  <>
                    <FileText size={20} />
                    Iniciar Análise NFe
                  </>
                )}
              </button>
            </div>
          </div>

          <div className="bg-amber-50/50 dark:bg-amber-900/10 p-6 rounded-[24px] border border-amber-100 dark:border-amber-900/20 flex gap-4">
            <AlertCircle className="text-amber-500 shrink-0" size={24} />
            <p className="text-xs text-amber-800 dark:text-amber-300 font-medium leading-relaxed">
              O motor de análise fiscal processa arquivos XML identificando divergências de destino, 
              impostos e cubagem em tempo real. Os resultados são gerados em relatório PDF após a conclusão.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default GrFiscalView;
