
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Search, Package, LayoutGrid, List, ArrowUpDown } from 'lucide-react';
import { API } from '../../api/client';
import type { AppInfo } from '../../api/client';
import { GlassCard } from '../ui/GlassCard';
import { AppDetailsView } from './AppDetails';

export function AppsView() {
    const [apps, setApps] = useState<AppInfo[]>([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [selectedApp, setSelectedApp] = useState<AppInfo | null>(null);
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [sortMode, setSortMode] = useState<'size' | 'name'>('size');

    useEffect(() => {
        loadApps();
    }, []);

    const loadApps = async () => {
        try {
            setLoading(true);
            const data = await API.getApps();
            // Initial load - sort logic handled in render/memo usually but let's just set raw data
            // Populate icons
            const appsWithIcons = await Promise.all(data.map(async (app) => {
                const icon = await API.getAppIcon(app.path);
                return { ...app, icon };
            }));

            setApps(appsWithIcons);
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const formatSize = (bytes: number) => {
        const units = ['B', 'KB', 'MB', 'GB'];
        let size = bytes;
        let unitIndex = 0;
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        return `${size.toFixed(1)} ${units[unitIndex]}`;
    };

    const sortedApps = [...apps].filter(app =>
        app.name.toLowerCase().includes(search.toLowerCase())
    ).sort((a, b) => {
        if (sortMode === 'size') {
            return b.size - a.size;
        } else {
            return a.name.localeCompare(b.name);
        }
    });

    if (selectedApp) {
        return (
            <AppDetailsView
                app={selectedApp}
                onBack={() => setSelectedApp(null)}
                onUninstall={() => {
                    loadApps();
                    setSelectedApp(null);
                }}
            />
        );
    }

    return (
        <div className="space-y-6 max-w-7xl mx-auto p-6 h-full flex flex-col">
            <header className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4 shrink-0">
                <div>
                    <h1 className="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-400 dark:from-blue-300 dark:to-purple-300">
                        App Uninstaller
                    </h1>
                    <p className="text-gray-500 dark:text-gray-400 mt-1">Scan and remove applications completely</p>
                </div>

                <div className="flex items-center gap-3 w-full md:w-auto">
                    {/* View Toggle */}
                    <div className="flex items-center bg-gray-100 dark:bg-white/5 rounded-lg p-1 border border-gray-200 dark:border-white/10">
                        <button
                            onClick={() => setViewMode('grid')}
                            className={`p-2 rounded-md transition-all ${viewMode === 'grid' ? 'bg-white dark:bg-white/10 shadow-sm text-blue-500' : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}`}
                        >
                            <LayoutGrid className="w-4 h-4" />
                        </button>
                        <button
                            onClick={() => setViewMode('list')}
                            className={`p-2 rounded-md transition-all ${viewMode === 'list' ? 'bg-white dark:bg-white/10 shadow-sm text-blue-500' : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}`}
                        >
                            <List className="w-4 h-4" />
                        </button>
                    </div>

                    {/* Sort Dropdown (Simple Toggle for now) */}
                    <button
                        onClick={() => setSortMode(prev => prev === 'size' ? 'name' : 'size')}
                        className="flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"
                    >
                        <ArrowUpDown className="w-4 h-4" />
                        <span>Sort by {sortMode === 'size' ? 'Size' : 'Name'}</span>
                    </button>

                    {/* Search */}
                    <div className="relative w-full md:w-64">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                        <input
                            type="text"
                            placeholder="Search apps..."
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                            className="w-full bg-white/50 dark:bg-black/20 border border-gray-200 dark:border-white/10 rounded-xl pl-10 pr-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50 transition-all text-gray-900 dark:text-white placeholder-gray-400"
                        />
                    </div>
                </div>
            </header>

            {loading ? (
                <div className="flex flex-col items-center justify-center py-32 text-gray-400">
                    <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mb-4" />
                    <p className="font-medium">Scanning applications...</p>
                </div>
            ) : (
                <div className="flex-1 overflow-y-auto pr-2 -mr-2">
                    {viewMode === 'grid' ? (
                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 pb-10">
                            <AnimatePresence>
                                {sortedApps.map((app) => (
                                    <motion.div
                                        key={app.path}
                                        initial={{ opacity: 0, scale: 0.95 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        exit={{ opacity: 0, scale: 0.95 }}
                                        layout
                                    >
                                        <GlassCard
                                            className="group hover:bg-white/80 dark:hover:bg-white/5 transition-all duration-300 cursor-pointer h-full border border-transparent hover:border-blue-500/20 hover:shadow-xl hover:shadow-blue-500/5 hover:-translate-y-1"
                                            onClick={() => setSelectedApp(app)}
                                        >
                                            <div className="flex flex-col items-center p-5 text-center h-full">
                                                <div className="w-16 h-16 mb-4 relative">
                                                    {app.icon ? (
                                                        <img src={app.icon} alt={app.name} className="w-full h-full object-contain drop-shadow-md" />
                                                    ) : (
                                                        <div className="w-full h-full rounded-xl bg-gradient-to-br from-blue-500/10 to-purple-500/10 flex items-center justify-center text-blue-400">
                                                            <Package className="w-8 h-8 opacity-50" />
                                                        </div>
                                                    )}
                                                </div>

                                                <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1 line-clamp-1 w-full text-sm md:text-base" title={app.name}>
                                                    {app.name}
                                                </h3>
                                                <p className="text-[10px] md:text-xs text-gray-500 dark:text-gray-400 font-mono mb-3 bg-gray-100 dark:bg-white/5 px-2 py-0.5 rounded-full">
                                                    {formatSize(app.size)}
                                                </p>
                                            </div>
                                        </GlassCard>
                                    </motion.div>
                                ))}
                            </AnimatePresence>
                        </div>
                    ) : (
                        // List View Logic
                        <div className="flex flex-col gap-2 pb-10">
                            {sortedApps.map((app) => (
                                <motion.div
                                    key={app.path}
                                    initial={{ opacity: 0, y: 10 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    className="group flex items-center gap-4 p-3 rounded-xl hover:bg-white/80 dark:hover:bg-white/5 border border-transparent hover:border-gray-200 dark:hover:border-white/10 transition-all cursor-pointer"
                                    onClick={() => setSelectedApp(app)}
                                >
                                    <div className="w-10 h-10 shrink-0">
                                        {app.icon ? (
                                            <img src={app.icon} alt={app.name} className="w-full h-full object-contain" />
                                        ) : (
                                            <div className="w-full h-full rounded-lg bg-blue-500/10 flex items-center justify-center">
                                                <Package className="w-5 h-5 text-blue-500" />
                                            </div>
                                        )}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate text-sm md:text-base">{app.name}</h3>
                                        <p className="text-[11px] md:text-xs text-gray-500 dark:text-gray-400 truncate">{app.path}</p>
                                    </div>
                                    <div className="shrink-0 text-xs md:text-sm font-mono text-gray-600 dark:text-gray-400">
                                        {formatSize(app.size)}
                                    </div>
                                </motion.div>
                            ))}
                        </div>
                    )}

                    {sortedApps.length === 0 && (
                        <div className="text-center py-20 text-gray-500">
                            No applications found matching "{search}"
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

