'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Loader2, Sparkles, AlertCircle, Clock, Cloud } from 'lucide-react';
import TastingEditor from './TastingEditor';
import SessionBottomSheet from './SessionBottomSheet';
import ResultCard from './ResultCard';
import { useSession } from '@/context/SessionContext';
import { enrichData } from '@/app/actions/enrich-data';
import { saveBottle } from '@/services/save-bottle';
import { saveTasting } from '@/services/save-tasting';
import { BottleMetadata } from '@/types/whisky';
import { useI18n } from '@/i18n/I18nContext';
import { createClient } from '@/lib/supabase/client';
import { useScanner, ScanStatus } from '@/hooks/useScanner';
import { db } from '@/lib/db';
import { useImageProcessor } from '@/hooks/useImageProcessor';

type FlowState = 'IDLE' | 'SCANNING' | 'EDITOR' | 'RESULT' | 'ERROR';

interface ScanAndTasteFlowProps {
    isOpen: boolean;
    onClose: () => void;
    imageFile: File | null;
    onBottleSaved?: (bottleId: string) => void;
}

export default function ScanAndTasteFlow({ isOpen, onClose, imageFile, onBottleSaved }: ScanAndTasteFlowProps) {
    const [state, setState] = useState<FlowState>('IDLE');
    const [isSessionsOpen, setIsSessionsOpen] = useState(false);
    const { activeSession } = useSession();
    const [tastingData, setTastingData] = useState<any>(null);
    const [bottleMetadata, setBottleMetadata] = useState<BottleMetadata | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [isSaving, setIsSaving] = useState(false);
    const { locale } = useI18n();
    const supabase = createClient();
    const [isAdmin, setIsAdmin] = useState(false);
    const [isOffline, setIsOffline] = useState(typeof navigator !== 'undefined' ? !navigator.onLine : false);
    const [isEnriching, setIsEnriching] = useState(false);
    const [aiFallbackActive, setAiFallbackActive] = useState(false);
    const [pendingTastingData, setPendingTastingData] = useState<any>(null);
    const { addToQueue } = useImageProcessor();

    // Use the AI-powered scanner hook
    const scanner = useScanner({
        locale,
        onComplete: (cloudResult) => {
            console.log('[ScanFlow] Gemma complete:', cloudResult);
            setBottleMetadata(cloudResult);

            // Trigger background enrichment if we have name and distillery
            if (cloudResult.name && cloudResult.distillery) {
                runEnrichment(cloudResult.name, cloudResult.distillery);
            }
        },
    });

    // Admin Check
    useEffect(() => {
        const checkAdmin = async () => {
            try {
                const { data: { user } } = await supabase.auth.getUser();
                if (user) {
                    const { data, error } = await supabase
                        .from('admin_users')
                        .select('role')
                        .eq('user_id', user.id)
                        .maybeSingle();

                    if (error) console.error('[ScanFlow] Admin check error:', error);
                    setIsAdmin(!!data);
                }
            } catch (err) {
                console.error('[ScanFlow] checkAdmin failed:', err);
            }
        };
        checkAdmin();
    }, [supabase]);

    // Background enrichment function
    const runEnrichment = useCallback(async (name: string, distillery: string) => {
        setIsEnriching(true);
        console.log('[ScanFlow] Starting background enrichment for:', name);
        try {
            const enrichResult = await enrichData(name, distillery, undefined, locale);
            if (enrichResult.success && enrichResult.data) {
                console.log('[ScanFlow] Enrichment data received:', enrichResult.data);
                setBottleMetadata(prev => {
                    if (!prev) return prev;
                    return {
                        ...prev,
                        suggested_tags: enrichResult.data.suggested_tags,
                        suggested_custom_tags: enrichResult.data.suggested_custom_tags,
                    };
                });
            } else {
                console.warn('[ScanFlow] Enrichment unsuccessful:', enrichResult.error);
            }
        } catch (err) {
            console.error('[ScanFlow] Enrichment failed:', err);
        } finally {
            setIsEnriching(false);
        }
    }, [locale]);

    // Trigger scan when open and image provided
    useEffect(() => {
        if (isOpen && imageFile) {
            setAiFallbackActive(false);
            handleScan(imageFile);
        } else if (!isOpen) {
            setState('IDLE');
            setTastingData(null);
            setBottleMetadata(null);
            setError(null);
            setIsSaving(false);
            setAiFallbackActive(false);
            scanner.reset();
        }
    }, [isOpen, imageFile]);

    // Online/Offline detection
    useEffect(() => {
        const handleOnline = () => setIsOffline(false);
        const handleOffline = () => setIsOffline(true);

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);

        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, []);

    // Sync scanner status to UI state
    useEffect(() => {
        const scannerStatus = scanner.status;

        if (scannerStatus === 'idle') {
            // Don't change state on idle
        } else if (scannerStatus === 'compressing') {
            setState('SCANNING');
        } else if (scannerStatus === 'editor_ready' || scannerStatus === 'analyzing') {
            // NEW: Open editor immediately when image is ready!
            if (scanner.mergedResult) {
                setBottleMetadata(scanner.mergedResult);
            }
            setState('EDITOR');
        } else if (scannerStatus === 'complete' || scannerStatus === 'queued') {
            if (scanner.mergedResult) {
                setBottleMetadata(scanner.mergedResult);
            }
            setState('EDITOR');

            if (scannerStatus === 'queued') {
                setAiFallbackActive(true);
                setIsOffline(true);
            }
        } else if (scannerStatus === 'error') {
            if (scanner.mergedResult) {
                setBottleMetadata(scanner.mergedResult);
                setState('EDITOR');
                setAiFallbackActive(true);
            } else {
                setError(scanner.error || 'Scan failed');
                setState('ERROR');
            }
        }
    }, [scanner.status, scanner.mergedResult, scanner.error]);

    const handleScan = async (file: File) => {
        setState('SCANNING');
        setError(null);
        scanner.handleScan(file);
    };

    const performSave = async (formData: any, currentMetadata: BottleMetadata) => {
        try {
            // ONLINE: Normal save to Supabase
            let user;
            try {
                const { data: { user: authUser } = {} } = await supabase.auth.getUser();
                if (!authUser) throw new Error('Nicht autorisiert');
                user = authUser;
            } catch (authError: any) {
                if (authError.message?.includes('Failed to fetch') || authError.message?.includes('NetworkError')) {
                    console.log('[ScanFlow] Auth failed due to network - switching to offline mode');
                    setIsOffline(true);
                    // Re-route back to original handleSaveTasting to trigger offline flow
                    return handleSaveTasting(formData);
                }
                throw authError;
            }

            const bottleDataToSave = formData.bottleMetadata || currentMetadata;
            const bottleResult = await saveBottle(bottleDataToSave, scanner.processedImage!.base64, user.id);

            if (!bottleResult.success || !bottleResult.data) {
                throw new Error(bottleResult.error || 'Fehler beim Speichern der Flasche');
            }

            const bottleId = bottleResult.data.id;

            // Queue for background removal
            if (scanner.processedImage?.file) {
                addToQueue(bottleId, scanner.processedImage.file);
            }

            const tastingNote = {
                ...formData,
                bottle_id: bottleId,
                session_id: activeSession?.id,
            };

            const tastingResult = await saveTasting(tastingNote);
            if (!tastingResult.success) {
                throw new Error(tastingResult.error || 'Fehler beim Speichern des Tastings');
            }

            setTastingData(tastingNote);
            setState('RESULT');

            if (onBottleSaved) {
                onBottleSaved(bottleId);
            }
        } catch (err: any) {
            setError(err.message);
            setState('ERROR');
        } finally {
            setIsSaving(false);
            setPendingTastingData(null);
        }
    };

    const handleSaveTasting = async (formData: any) => {
        if (!scanner.mergedResult || !scanner.processedImage) return;

        setIsSaving(true);
        setError(null);

        // If AI is still analyzing, put in "pending" status
        if (scanner.isAnalyzing) {
            console.log('[ScanFlow] AI still analyzing - queuing save');
            setPendingTastingData(formData);
            return;
        }

        try {
            // OFFLINE: Save to IndexedDB queue
            if (isOffline) {
                console.log('[ScanFlow] Offline mode - queuing for upload');
                const tempId = `temp_${Date.now()}`;
                const bottleDataToSave = formData.bottleMetadata || scanner.mergedResult;

                const existingScan = await db.pending_scans
                    .filter(s => s.imageBase64 === scanner.processedImage!.base64)
                    .first();

                let currentTempId = tempId;

                if (existingScan) {
                    console.log('[ScanFlow] Existing pending scan found, reusing temp_id:', existingScan.temp_id);
                    currentTempId = existingScan.temp_id;
                } else {
                    await db.pending_scans.add({
                        temp_id: tempId,
                        imageBase64: scanner.processedImage.base64,
                        timestamp: Date.now(),
                        locale,
                        metadata: bottleDataToSave as any
                    });

                    // Queue for background removal using temp_id
                    if (scanner.processedImage?.file) {
                        addToQueue(tempId, scanner.processedImage.file);
                    }
                }

                await db.pending_tastings.add({
                    pending_bottle_id: currentTempId,
                    data: {
                        session_id: activeSession?.id,
                        rating: formData.rating,
                        nose_notes: formData.nose_notes,
                        palate_notes: formData.palate_notes,
                        finish_notes: formData.finish_notes,
                        is_sample: formData.is_sample,
                        buddy_ids: formData.buddy_ids,
                        tag_ids: formData.tag_ids,
                    },
                    tasted_at: new Date().toISOString()
                });

                setTastingData(formData);
                setState('RESULT');
                setIsSaving(false);
                return;
            }

            // Normal online save
            await performSave(formData, scanner.mergedResult);

        } catch (err: any) {
            setError(err.message);
            setState('ERROR');
            setIsSaving(false);
        }
    };

    // New Effect: Watch for AI completion if we have a pending save
    useEffect(() => {
        if (!scanner.isAnalyzing && pendingTastingData && scanner.mergedResult) {
            console.log('[ScanFlow] AI finished, triggering pending save');
            performSave(pendingTastingData, scanner.mergedResult);
        }
    }, [scanner.isAnalyzing, pendingTastingData, scanner.mergedResult]);

    const handleShare = async () => {
        if (navigator.share) {
            try {
                await navigator.share({
                    title: `My Tasting: ${bottleMetadata?.name || 'Whisky'}`,
                    text: `Check out my tasting results for ${bottleMetadata?.distillery} ${bottleMetadata?.name}!`,
                    url: window.location.href,
                });
            } catch (err) {
                console.error('Share failed:', err);
            }
        } else {
            alert('Sharing is not supported on this browser.');
        }
    };

    const getScanStatusDisplay = (status: ScanStatus): { text: string; icon: React.ReactNode } => {
        switch (status) {
            case 'compressing':
                return { text: 'Bild optimieren...', icon: <Loader2 size={12} className="animate-spin" /> };
            case 'analyzing':
                return { text: 'KI-Vision-Analyse...', icon: <Cloud size={12} /> };
            default:
                return { text: 'Analysiere Etikett...', icon: <Loader2 size={12} className="animate-spin" /> };
        }
    };

    const statusDisplay = getScanStatusDisplay(scanner.status);

    return (
        <AnimatePresence>
            {isOpen && (
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="fixed inset-0 z-[60] bg-zinc-950 flex flex-col h-[100dvh] w-screen overflow-hidden overscroll-none"
                >
                    {/* Close Button */}
                    <button
                        onClick={onClose}
                        className="absolute top-6 right-6 z-[70] p-2 rounded-full bg-zinc-900 border border-zinc-800 text-zinc-400 hover:text-white transition-colors"
                    >
                        <X size={24} />
                    </button>

                    <div className="flex-1 w-full h-full flex flex-col relative min-h-0">
                        {(state === 'SCANNING' || (state === 'IDLE' && imageFile)) && (
                            <div className="flex-1 flex flex-col items-center justify-center">
                                <motion.div
                                    initial={{ scale: 0.9, opacity: 0 }}
                                    animate={{ scale: 1, opacity: 1 }}
                                    className="flex flex-col items-center gap-6"
                                >
                                    <div className="relative">
                                        <motion.div
                                            animate={{ rotate: 360 }}
                                            transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
                                            className="w-32 h-32 rounded-full border-2 border-dashed border-orange-600/30"
                                        />
                                        <div className="absolute inset-0 flex items-center justify-center">
                                            <Loader2 size={48} className="animate-spin text-orange-600" />
                                        </div>
                                    </div>
                                    <div className="text-center space-y-2">
                                        <h2 className="text-2xl font-bold text-zinc-50 uppercase tracking-tight">Analysiere Etikett...</h2>
                                        <p className="text-orange-500 font-bold uppercase tracking-widest text-[10px] flex items-center justify-center gap-2">
                                            {statusDisplay.icon}
                                            {statusDisplay.text}
                                        </p>
                                        {/* Show scan stage indicators */}
                                        <div className="flex items-center justify-center gap-2 mt-4">
                                            <div className={`w-2 h-2 rounded-full transition-colors ${['compressing', 'analyzing', 'complete'].includes(scanner.status)
                                                ? 'bg-orange-500' : 'bg-zinc-700'
                                                }`} />
                                            <div className={`w-2 h-2 rounded-full transition-colors ${['analyzing', 'complete'].includes(scanner.status)
                                                ? 'bg-orange-500' : 'bg-zinc-700'
                                                }`} />
                                        </div>
                                    </div>
                                </motion.div>

                                {/* Admin perf metrics */}
                                {isAdmin && scanner.perf && (
                                    <div className="mt-8 p-6 bg-zinc-950/80 backdrop-blur-xl rounded-3xl border border-orange-500/20 text-[10px] font-mono text-zinc-400 animate-in fade-in slide-in-from-bottom-4 shadow-2xl">
                                        <div className="grid grid-cols-2 gap-6 text-center">
                                            <div>
                                                <p className="text-zinc-500 mb-2 uppercase tracking-widest text-[8px]">Compress</p>
                                                <p className="text-orange-500 font-bold">{scanner.perf.compression.toFixed(0)}ms</p>
                                            </div>
                                            <div>
                                                <p className="text-zinc-500 mb-2 uppercase tracking-widest text-[8px]">Cloud Vision</p>
                                                <p className="text-orange-500 font-bold">{scanner.perf.cloudVision.toFixed(0)}ms</p>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}

                        {state === 'ERROR' && (
                            <div className="flex-1 flex flex-col items-center justify-center">
                                <motion.div
                                    initial={{ scale: 0.9, opacity: 0 }}
                                    animate={{ scale: 1, opacity: 1 }}
                                    className="flex flex-col items-center gap-6 p-8 text-center"
                                >
                                    <div className="w-20 h-20 rounded-full bg-red-500/10 flex items-center justify-center text-red-500">
                                        <AlertCircle size={40} />
                                    </div>
                                    <div className="space-y-2">
                                        <h2 className="text-2xl font-display font-bold text-white uppercase tracking-tight">Ups! Da lief was schief.</h2>
                                        <p className="text-white/60 text-sm max-w-xs mx-auto font-sans">{error || 'Wir konnten die Flasche leider nicht erkennen. Bitte versuch es mit einem anderen Foto.'}</p>
                                    </div>
                                    <button
                                        onClick={onClose}
                                        className="px-8 py-4 bg-white text-[#0F1014] rounded-2xl font-sans font-bold uppercase tracking-widest text-[10px] hover:bg-white/90 transition-all"
                                    >
                                        Schließen
                                    </button>
                                </motion.div>
                            </div>
                        )}

                        {state === 'EDITOR' && bottleMetadata && (
                            <motion.div
                                key="editor"
                                initial={{ y: 50, opacity: 0 }}
                                animate={{ y: 0, opacity: 1 }}
                                exit={{ y: -50, opacity: 0 }}
                                className="flex-1 w-full h-full flex flex-col min-h-0"
                            >
                                {/* AI Analyzing Banner - shows when AI is still processing */}
                                {scanner.isAnalyzing && (
                                    <div className="bg-blue-500/10 border-b border-blue-500/20 p-3">
                                        <div className="max-w-2xl mx-auto flex items-center gap-3">
                                            <Loader2 size={14} className="animate-spin text-blue-500" />
                                            <p className="text-xs font-bold text-blue-500 uppercase tracking-wider">
                                                KI analysiert Etikett...
                                            </p>
                                        </div>
                                    </div>
                                )}

                                {/* Status banners */}
                                {isOffline && (
                                    <div className="bg-orange-500/10 border-b border-orange-500/20 p-4">
                                        <div className="max-w-2xl mx-auto flex items-center gap-3">
                                            <div className="w-2 h-2 rounded-full bg-orange-500 animate-pulse" />
                                            <p className="text-xs font-bold text-orange-500 uppercase tracking-wider">
                                                {aiFallbackActive
                                                    ? 'KI-Dienst nicht erreichbar. Nutze Platzhalter-Daten; Anreicherung erfolgt automatisch im Hintergrund.'
                                                    : 'Offline Modus - Daten werden hochgeladen wenn du online bist'}
                                            </p>
                                        </div>
                                    </div>
                                )}

                                <TastingEditor
                                    bottleMetadata={bottleMetadata}
                                    image={scanner.processedImage?.base64 || null}
                                    onSave={handleSaveTasting}
                                    onOpenSessions={() => setIsSessionsOpen(true)}
                                    activeSessionName={activeSession?.name}
                                    activeSessionId={activeSession?.id}
                                    isEnriching={isEnriching}
                                    defaultExpanded={true}
                                />

                                {/* Admin perf overlay */}
                                {isAdmin && scanner.perf && (
                                    <div className="fixed bottom-24 left-6 right-6 z-50 p-3 bg-zinc-950/80 backdrop-blur-md rounded-2xl border border-orange-500/20 text-[9px] font-mono text-white/90 shadow-xl overflow-x-auto">
                                        <div className="flex items-center justify-between gap-4 whitespace-nowrap">
                                            {scanner.perf.model && (
                                                <div className="flex items-center gap-2">
                                                    <span className="text-zinc-500">MODEL:</span>
                                                    <span className="text-purple-400 font-bold">{scanner.perf.model}</span>
                                                </div>
                                            )}
                                            <div className="flex items-center gap-2">
                                                <Clock size={10} className="text-orange-500" />
                                                <span className="text-zinc-500">COMPRESS:</span>
                                                <span className="text-orange-500 font-bold">{scanner.perf.compression.toFixed(0)}ms</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <span className="text-zinc-500">AI:</span>
                                                <span className="text-green-500 font-bold">{scanner.perf.cloudVision.toFixed(0)}ms</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <span className="text-zinc-500">TOTAL:</span>
                                                <span className="text-orange-500 font-bold">{scanner.perf.total.toFixed(0)}ms</span>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </motion.div>
                        )}

                        {(isSaving) && (
                            <motion.div
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 1 }}
                                className="absolute inset-0 z-[80] bg-zinc-950/80 backdrop-blur-sm flex flex-col items-center justify-center gap-6"
                            >
                                <Loader2 size={48} className="animate-spin text-orange-600" />
                                <h2 className="text-xl font-bold text-zinc-50 uppercase tracking-tight">
                                    {scanner.isAnalyzing ? 'Warte auf Analyse...' : 'Speichere Tasting...'}
                                </h2>
                                {scanner.isAnalyzing && (
                                    <p className="text-[10px] text-zinc-500 font-bold uppercase tracking-[0.2em] animate-pulse">
                                        KI verarbeitet Etikett-Details
                                    </p>
                                )}
                            </motion.div>
                        )}

                        {state === 'RESULT' && tastingData && bottleMetadata && (
                            <div className="flex-1 overflow-y-auto">
                                <div className="min-h-full flex flex-col items-center justify-center py-20 px-6">
                                    <motion.div
                                        key="result"
                                        initial={{ scale: 0.8, opacity: 0 }}
                                        animate={{ scale: 1, opacity: 1 }}
                                        className="w-full max-w-sm"
                                    >
                                        <ResultCard
                                            data={{
                                                ...tastingData,
                                                complexity: tastingData.complexity || 75,
                                                balance: tastingData.balance || 85,
                                            }}
                                            bottleName={bottleMetadata.name || 'Unknown Whisky'}
                                            image={scanner.processedImage?.base64 || null}
                                            onShare={handleShare}
                                        />
                                    </motion.div>
                                </div>
                            </div>
                        )}
                    </div>

                    <SessionBottomSheet
                        isOpen={isSessionsOpen}
                        onClose={() => setIsSessionsOpen(false)}
                    />
                </motion.div>
            )}
        </AnimatePresence>
    );
}
