import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { Bug, ChevronUp, ChevronDown, User, X, Sprout, Loader2 } from 'lucide-react';
import api from '../../lib/api';

interface DevUser {
    email: string;
    password: string;
    name: string;
    role: string;
    color: string;
}

const DEV_USERS: DevUser[] = [
    { email: 'admin@runfoo.run', password: 'password123', name: 'Travis (Owner)', role: 'OWNER', color: 'bg-[var(--color-primary)]' },
    { email: 'sarah@demo.local', password: 'demo1234', name: 'Sarah Chen (Manager)', role: 'MANAGER', color: 'bg-purple-500' },
    { email: 'mike@demo.local', password: 'demo1234', name: 'Mike Thompson (Grower)', role: 'GROWER', color: 'bg-green-500' },
    { email: 'alex@demo.local', password: 'demo1234', name: 'Alex Rivera (Staff)', role: 'STAFF', color: 'bg-[var(--color-accent)]' },
];

/**
 * Development-only tool for quick user switching
 * Only renders when VITE_DEV_TOOLS=true or in development mode
 */
export function DevTools() {
    const { user, login, logout } = useAuth();
    const navigate = useNavigate();
    const [isOpen, setIsOpen] = useState(false);
    const [isLoading, setIsLoading] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    // Show in development, when explicitly enabled, or on testing domains (*.runfoo.run)
    const isTestingDomain = typeof window !== 'undefined' && window.location.hostname.endsWith('runfoo.run');
    const isDev = import.meta.env.DEV || import.meta.env.VITE_DEV_TOOLS === 'true' || isTestingDomain;
    if (!isDev) return null;

    const handleQuickLogin = async (devUser: DevUser) => {
        setIsLoading(devUser.email);
        setError(null);

        try {
            // If already logged in, logout first
            if (user) {
                logout();
                // Small delay to let state settle
                await new Promise(resolve => setTimeout(resolve, 100));
            }

            const response = await api.post('/auth/login', {
                email: devUser.email,
                password: devUser.password
            });

            const { accessToken, refreshToken, user: userData } = response.data;
            login(accessToken, refreshToken, userData);
            setIsOpen(false);
            // Navigate to dashboard after successful account switch
            navigate('/');
        } catch (err: any) {
            setError(err.response?.data?.message || 'Login failed - run seed first?');
        } finally {
            setIsLoading(null);
        }
    };

    const [isReseeding, setIsReseeding] = useState(false);
    const [reseedResult, setReseedResult] = useState<string | null>(null);

    const handleReseedPlants = async () => {
        if (!user) {
            setError('Must be logged in as OWNER or ADMIN to reseed');
            return;
        }

        setIsReseeding(true);
        setError(null);
        setReseedResult(null);

        try {
            const response = await api.post('/admin/reseed-plants');
            setReseedResult(`✅ ${response.data.totalPlants} plants placed`);
        } catch (err: any) {
            setError(err.response?.data?.error || 'Reseed failed');
        } finally {
            setIsReseeding(false);
        }
    };

    return (
        <div className="fixed bottom-20 md:bottom-4 right-4 z-50">
            {/* Toggle Button */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="w-12 h-12 rounded-full bg-[var(--color-warning)] hover:bg-amber-600 text-white shadow-lg flex items-center justify-center transition-all hover:scale-105"
                title="Dev Tools"
            >
                <Bug size={20} />
            </button>

            {/* Panel */}
            {isOpen && (
                <div className="absolute bottom-14 right-0 w-72 bg-[var(--color-bg-elevated)] rounded-xl shadow-2xl border border-[var(--color-border-default)] overflow-hidden animate-scale-in">
                    {/* Header */}
                    <div className="bg-[var(--color-warning)] text-white px-4 py-3 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <Bug size={18} />
                            <span className="font-bold text-sm">Dev Tools</span>
                        </div>
                        <button onClick={() => setIsOpen(false)} className="hover:bg-amber-600 rounded p-1">
                            <X size={16} />
                        </button>
                    </div>

                    {/* Current User */}
                    <div className="px-4 py-3 border-b border-[var(--color-border-default)]">
                        <p className="text-[10px] uppercase text-[var(--color-text-tertiary)] font-semibold mb-1">Current User</p>
                        {user ? (
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-[var(--color-text-primary)]">{user.name || user.email}</p>
                                    <p className="text-xs text-[var(--color-text-tertiary)]">{user.role}</p>
                                </div>
                                <button
                                    onClick={logout}
                                    className="text-xs text-red-600 hover:text-red-700 font-medium"
                                >
                                    Logout
                                </button>
                            </div>
                        ) : (
                            <p className="text-sm text-[var(--color-text-tertiary)] italic">Not logged in</p>
                        )}
                    </div>

                    {/* Quick Switch */}
                    <div className="px-4 py-3">
                        <p className="text-[10px] uppercase text-[var(--color-text-tertiary)] font-semibold mb-2">Quick Switch</p>
                        <div className="space-y-2">
                            {DEV_USERS.map(devUser => (
                                <button
                                    key={devUser.email}
                                    onClick={() => handleQuickLogin(devUser)}
                                    disabled={isLoading !== null}
                                    className={`w-full flex items-center gap-3 p-2 rounded-lg text-left transition-all ${user?.email === devUser.email
                                        ? 'bg-emerald-50 dark:bg-emerald-900/20 border-2 border-emerald-500'
                                        : 'bg-slate-50 dark:bg-slate-700/50 hover:bg-slate-100 dark:hover:bg-slate-700 border-2 border-transparent'
                                        } ${isLoading === devUser.email ? 'opacity-50' : ''}`}
                                >
                                    <div className={`w-8 h-8 rounded-full ${devUser.color} flex items-center justify-center text-white text-xs font-bold`}>
                                        {devUser.name[0]}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className="text-sm font-medium text-[var(--color-text-primary)] truncate">
                                            {devUser.name}
                                        </p>
                                        <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase">{devUser.role}</p>
                                    </div>
                                    {isLoading === devUser.email && (
                                        <div className="w-4 h-4 border-2 border-slate-300 border-t-slate-600 rounded-full animate-spin" />
                                    )}
                                    {user?.email === devUser.email && (
                                        <div className="w-2 h-2 rounded-full bg-[var(--color-primary)]" />
                                    )}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Demo Actions */}
                    {user && ['OWNER', 'ADMIN'].includes(user.role) && (
                        <div className="px-4 py-3 border-t border-[var(--color-border-default)]">
                            <p className="text-[10px] uppercase text-[var(--color-text-tertiary)] font-semibold mb-2">Demo Actions</p>
                            <button
                                onClick={handleReseedPlants}
                                disabled={isReseeding}
                                className="w-full flex items-center justify-center gap-2 p-2 rounded-lg text-sm bg-green-600 hover:bg-green-700 text-white transition-all disabled:opacity-50"
                            >
                                {isReseeding ? (
                                    <Loader2 size={16} className="animate-spin" />
                                ) : (
                                    <Sprout size={16} />
                                )}
                                Reseed Demo Plants
                            </button>
                            {reseedResult && (
                                <p className="text-xs text-green-600 mt-2 text-center">{reseedResult}</p>
                            )}
                        </div>
                    )}

                    {/* Error */}
                    {error && (
                        <div className="px-4 pb-3">
                            <p className="text-xs text-red-600 bg-red-50 dark:bg-red-900/20 p-2 rounded">
                                {error}
                            </p>
                        </div>
                    )}

                    {/* Footer */}
                    <div className="px-4 py-2 bg-[var(--color-bg-tertiary)] border-t border-[var(--color-border-default)]">
                        <p className="text-[10px] text-[var(--color-text-tertiary)] text-center">
                            🚧 Testing Environment Only
                        </p>
                    </div>
                </div>
            )}
        </div>
    );
}
