import React, { useState } from 'react';
import Header from '../components/Header';
import { useAuth } from '../AuthContext';
import { motion } from 'framer-motion';
import { Brain, Upload, Image as ImageIcon, AlertCircle } from 'lucide-react';
import NeuroScorecard from '../components/NeuroScorecard';
import { ApiKeyModal } from '../components/ApiKeyModal';

const ScorecardPage = () => {
    const { user, token, logout, refreshUser } = useAuth();
    const [imageUrl, setImageUrl] = useState<string>('');
    const [loading, setLoading] = useState(false);
    const [analysis, setAnalysis] = useState<any>(null);
    const [error, setError] = useState<string | null>(null);
    const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false);

    const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImageUrl(reader.result as string);
                setAnalysis(null); // Reset analysis when new image is uploaded
            };
            reader.readAsDataURL(file);
        }
    };

    const analyzeImage = async () => {
        if (!imageUrl) return;

        setLoading(true);
        setError(null);

        try {
            // Strip base64 prefix if present for API
            const base64Data = imageUrl.split(',')[1];

            const response = await fetch('http://localhost:3001/api/neuro-score', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    imageBase64: base64Data,
                    apiKey: localStorage.getItem('gemini_api_key') || user?.apiKey // BYOK support
                })
            });

            const data = await response.json();

            if (!data.success) {
                throw new Error(data.error || "Analysis failed");
            }

            setAnalysis(data.data);

        } catch (err: any) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-stone-950 text-stone-200 font-sans selection:bg-purple-500/30">
            <Header
                user={user}
                logout={logout}
                openApiKeyModal={() => setIsApiKeyModalOpen(true)}
            />

            <ApiKeyModal
                isOpen={isApiKeyModalOpen}
                onClose={() => setIsApiKeyModalOpen(false)}
            />

            <main className="max-w-6xl mx-auto px-6 py-12">

                {/* Hero Section */}
                <div className="text-center mb-16">
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-blue-500/10 border border-blue-500/20 text-blue-400 text-sm font-medium mb-6"
                    >
                        <Brain className="w-4 h-4" />
                        <span>The Internal Critic</span>
                    </motion.div>

                    <h1 className="text-5xl md:text-6xl font-serif text-white mb-6">
                        Neuro-Scorecard
                    </h1>
                    <p className="text-xl text-stone-400 max-w-2xl mx-auto leading-relaxed">
                        Don't guess what sells. Let our AI predict your conversion rate by analyzing
                        dopamine triggers, cognitive ease, and market fit.
                    </p>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start">

                    {/* Input Section */}
                    <div className="space-y-6">
                        <div className="p-8 rounded-3xl bg-stone-900/50 border border-white/5 backdrop-blur-sm relative group overflow-hidden">
                            <div className="absolute inset-0 bg-gradient-to-br from-blue-500/5 to-purple-500/5 opacity-0 group-hover:opacity-100 transition-opacity" />

                            {!imageUrl ? (
                                <label className="flex flex-col items-center justify-center w-full h-80 border-2 border-dashed border-white/10 rounded-xl cursor-pointer hover:border-blue-500/50 hover:bg-white/5 transition-all group-hover:scale-[1.02]">
                                    <div className="flex flex-col items-center justify-center pt-5 pb-6">
                                        <div className="p-4 bg-stone-800 rounded-full mb-4">
                                            <Upload className="w-8 h-8 text-stone-400" />
                                        </div>
                                        <p className="mb-2 text-lg text-stone-300 font-medium">Click to upload an image</p>
                                        <p className="text-sm text-stone-500">PNG, JPG up to 10MB</p>
                                    </div>
                                    <input type="file" className="hidden" accept="image/*" onChange={handleImageUpload} />
                                </label>
                            ) : (
                                <div className="relative rounded-xl overflow-hidden shadow-2xl">
                                    <img src={imageUrl} alt="Analysis Target" className="w-full h-auto object-cover" />
                                    <button
                                        onClick={() => { setImageUrl(''); setAnalysis(null); }}
                                        className="absolute top-4 right-4 p-2 bg-black/50 backdrop-blur-md rounded-full text-white hover:bg-red-500/80 transition-colors"
                                    >
                                        <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                            <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                                        </svg>
                                    </button>
                                </div>
                            )}
                        </div>

                        <button
                            onClick={analyzeImage}
                            disabled={!imageUrl || loading}
                            className={`w-full py-4 rounded-xl font-bold text-lg shadow-lg flex items-center justify-center gap-2 transition-all ${!imageUrl ? 'bg-stone-800 text-stone-500 cursor-not-allowed' :
                                loading ? 'bg-stone-700 text-stone-400 cursor-wait' :
                                    'bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-500 hover:to-purple-500 text-white hover:shadow-blue-500/20 hover:scale-[1.02]'
                                }`}
                        >
                            {loading ? (
                                <>Processing Vision...</>
                            ) : (
                                <>
                                    <Brain className="w-5 h-5" />
                                    Run Neuro-Analysis
                                </>
                            )}
                        </button>

                        {error && (
                            <motion.div
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                className="p-4 bg-red-500/10 border border-red-500/20 rounded-xl text-red-400 flex items-center gap-3"
                            >
                                <AlertCircle className="w-5 h-5 flex-shrink-0" />
                                <p>{error}</p>
                            </motion.div>
                        )}
                    </div>

                    {/* Results Section */}
                    <div>
                        {!analysis && !loading && (
                            <div className="h-full flex flex-col items-center justify-center text-stone-600 p-12 border border-white/5 rounded-3xl bg-stone-900/30 border-dashed">
                                <ImageIcon className="w-16 h-16 mb-4 opacity-20" />
                                <p className="text-lg font-medium">Ready to Score</p>
                                <p className="text-sm">Upload an image to see its commercial prediction.</p>
                            </div>
                        )}

                        {(analysis || loading) && (
                            <NeuroScorecard analysis={analysis} loading={loading} />
                        )}
                    </div>

                </div>
            </main>
        </div>
    );
};

export default ScorecardPage;
