import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Camera, Upload, CheckCircle2, Loader2, FileImage } from 'lucide-react';
import { supabase } from '../lib/supabase';
import { useAuth } from '../contexts/AuthContext';

export default function UploadInvoice() {
  const { user, isLoading: authLoading } = useAuth();
  const navigate = useNavigate();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [file, setFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Redirect if not logged in
  useEffect(() => {
    if (authLoading) return;
    if (!user && !loading && !success) {
      navigate('/auth');
    }
  }, [user, authLoading, loading, success, navigate]);

  if (authLoading || (!user && !loading && !success)) {
    return null;
  }

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (selectedFile.size > 5 * 1024 * 1024) {
        setError('La imagen no debe superar los 5MB.');
        return;
      }
      setFile(selectedFile);
      setPreviewUrl(URL.createObjectURL(selectedFile));
      setError(null);
    }
  };

  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };

  const handleSubmit = async () => {
    if (!file || !user) return;
    
    setLoading(true);
    setError(null);

    try {
      const webhookUrl = import.meta.env.VITE_N8N_WEBHOOK_URL;
      if (!webhookUrl) {
         throw new Error("La URL del webhook no está configurada.");
      }

      const formData = new FormData();
      formData.append('file', file);
      formData.append('user_id', user.id);

      const response = await fetch(webhookUrl, {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error("No pudimos procesar la factura. Intenta de nuevo.");
      }

      setSuccess(true);
      
    } catch (err: any) {
      console.error(err);
      setError(err.message || "Ocurrió un error inesperado.");
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center p-6 animate-in zoom-in duration-300">
         <div className="bg-white rounded-[3rem] p-8 text-center max-w-sm w-full shadow-2xl relative overflow-hidden">
            <div className="absolute top-0 right-0 -mr-16 -mt-16 w-32 h-32 bg-brand-yellow/30 rounded-full blur-2xl"></div>
            
            <div className="w-20 h-20 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-6">
              <CheckCircle2 size={40} className="drop-shadow-sm" />
            </div>
            
            <h2 className="font-display text-4xl text-brand-navy uppercase mb-4 leading-none">¡Factura Enviada!</h2>
            
            <p className="text-brand-navy/80 font-medium mb-8 leading-relaxed">
              Tu ticket está en revisión por nuestro sistema. Pronto verás tus puntos reflejados.
            </p>

            <button 
              onClick={() => navigate('/dashboard')}
              className="w-full bg-brand-navy text-white font-display text-xl uppercase py-4 rounded-2xl hover:bg-brand-navy/90 transition-all active:scale-95"
            >
              Ver mi progreso
            </button>
         </div>
      </div>
    );
  }

  return (
    <div className="flex-1 p-4 pb-12 flex flex-col animate-in fade-in duration-300">
      <div className="max-w-md w-full mx-auto mt-4">
        
        <div className="text-center mb-8">
          <h1 className="font-display text-4xl uppercase text-brand-yellow drop-shadow-md mb-2">
            Registrar Factura
          </h1>
          <p className="text-white/90 font-medium">
            Sube una foto clara de tu ticket
          </p>
        </div>

        <div className="bg-white rounded-[2.5rem] p-6 shadow-xl text-brand-navy">
          
          {error && (
            <div className="bg-brand-red/10 text-brand-red p-4 rounded-2xl mb-6 text-sm border border-brand-red/20 text-center font-medium">
              {error}
            </div>
          )}

          <div 
            onClick={handleUploadClick}
            className={`border-3 border-dashed rounded-3xl p-8 flex flex-col items-center justify-center text-center cursor-pointer transition-all ${
              previewUrl ? 'border-brand-blue/30 bg-brand-blue/5' : 'border-black/10 bg-brand-cream hover:bg-brand-yellow/10 hover:border-brand-yellow'
            }`}
          >
            {previewUrl ? (
              <div className="relative w-full aspect-[3/4] max-h-64 rounded-2xl overflow-hidden shadow-inner">
                <img src={previewUrl} alt="Preview" className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
                   <p className="text-white font-bold inline-flex items-center gap-2">
                      <Camera size={20} /> Cambiar Foto
                   </p>
                </div>
              </div>
            ) : (
              <div className="py-8 flex flex-col items-center">
                <div className="w-16 h-16 bg-brand-yellow text-brand-navy rounded-full flex items-center justify-center mb-4 shadow-sm">
                  <Upload size={28} />
                </div>
                <h3 className="font-bold text-lg mb-1">Toca para subir</h3>
                <p className="text-brand-navy/60 text-sm max-w-[200px]">Formatos: JPG, PNG. Máximo 5MB.</p>
              </div>
            )}
            <input 
              type="file" 
              ref={fileInputRef} 
              onChange={handleFileChange} 
              accept="image/jpeg, image/png, image/webp" 
              className="hidden" 
            />
          </div>

          <button
            onClick={handleSubmit}
            disabled={!file || loading}
            className={`mt-6 w-full ${loading ? 'bg-brand-blue/80 opacity-100' : 'bg-brand-blue hover:bg-brand-blue/90'} ${!file && !loading ? 'opacity-50' : ''} text-white font-display text-lg uppercase py-4 rounded-2xl active:scale-[0.98] transition-all flex flex-col items-center justify-center gap-1 disabled:pointer-events-none shadow-lg shadow-brand-blue/20`}
          >
            {loading ? (
               <>
                 <Loader2 className="animate-spin mb-1" size={24} />
                 <span className="text-sm normal-case font-medium">Analizando tu factura con Inteligencia Artificial... por favor espera</span>
               </>
            ) : (
               <span className="text-xl">Enviar Factura</span>
            )}
          </button>
          
        </div>
      </div>
    </div>
  );
}
