import React, { useState, useEffect, useCallback } from 'react';
import { Toaster } from 'react-hot-toast';
import toast from 'react-hot-toast';
import {
  Moon, Sun, LogOut, FolderOpen, Settings as SettingsIcon,
  HardDrive, User, Trash2, ChevronUp
} from 'lucide-react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { getMe, fetchCsrf, getUsage, getTrashCount, logout as apiLogout } from './api';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Settings from './pages/Settings';

function getPage() {
  const path = window.location.pathname.replace(window.__BASE_PATH__ || '', '');
  if (path === '/login') return 'login';
  if (path === '/app/settings') return 'settings';
  if (path === '/app/trash') return 'trash';
  return 'dashboard';
}

function navigate(to) {
  const base = window.__BASE_PATH__ || '';
  window.history.pushState({}, '', base + to);
  window.dispatchEvent(new Event('popstate'));
}

export default function App() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(getPage);
  const [theme, setTheme] = useState(() => localStorage.getItem('sfiles_theme') || 'paper');
  const [usage, setUsage] = useState(null);
  const [trashCount, setTrashCount] = useState(0);
  const [startOpen, setStartOpen] = useState(false);

  useEffect(() => {
    const root = document.documentElement;
    root.className = theme === 'midnight' ? 'theme-midnight' : 'theme-paper';
    localStorage.setItem('sfiles_theme', theme);
  }, [theme]);

  useEffect(() => {
    const handler = () => setPage(getPage());
    window.addEventListener('popstate', handler);
    return () => window.removeEventListener('popstate', handler);
  }, []);

  const loadUsage = useCallback(async () => {
    try {
      const res = await getUsage();
      setUsage(res.data);
    } catch {}
  }, []);

  const loadTrashCount = useCallback(async () => {
    try {
      const res = await getTrashCount();
      setTrashCount(res.data.count || 0);
    } catch {}
  }, []);

  const checkAuth = useCallback(async () => {
    try {
      await fetchCsrf();
      const res = await getMe();
      setUser(res.data);
      loadUsage();
      loadTrashCount();
    } catch {
      setUser(null);
      if (getPage() !== 'login') navigate('/login');
    } finally {
      setLoading(false);
    }
  }, [loadUsage, loadTrashCount]);

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

  const onLoginSuccess = (u) => {
    setUser(u);
    navigate('/app');
    loadUsage();
    loadTrashCount();
  };

  const onLogout = async () => {
    try { await apiLogout(); toast.success('Berhasil keluar'); } catch {}
    setUser(null);
    navigate('/login');
  };

  const toggleTheme = () => setTheme(t => t === 'paper' ? 'midnight' : 'paper');

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="window-card" style={{ width: 340 }}>
          <div className="window-header">
            <div className="window-dots">
              <div className="window-dot window-dot-red" />
              <div className="window-dot window-dot-yellow" />
              <div className="window-dot window-dot-green" />
            </div>
            <div className="window-title">Syamsu Files</div>
          </div>
          <div className="window-body flex flex-col items-center gap-4 py-10">
            <div className="text-4xl animate-bounce">📂</div>
            <div className="progress-track w-48">
              <div className="progress-fill" style={{ width: '65%' }} />
              <div className="progress-text">Memuat...</div>
            </div>
            <p style={{ color: 'var(--ink-muted)', fontSize: 13 }}>Memeriksa sesi...</p>
          </div>
        </div>
      </div>
    );
  }

  if (!user || page === 'login') {
    return (
      <>
        <Toaster position="top-center" toastOptions={{ className: 'toast-scrapbook', duration: 3000 }} />
        <Login onSuccess={onLoginSuccess} theme={theme} toggleTheme={toggleTheme} />
      </>
    );
  }

  return (
    <>
      <Toaster position="top-center" toastOptions={{ className: 'toast-scrapbook', duration: 3000 }} />
      <div className="app-shell">
        <span className="deco-sparkle" style={{ top: 16, left: 14 }}>✦</span>
        <span className="deco-sparkle" style={{ top: 50, right: 24 }}>✧</span>
        <span className="deco-sparkle" style={{ bottom: 60, left: 36 }}>⊹</span>
        <span className="deco-sparkle" style={{ bottom: 60, right: 14 }}>✦</span>

        <div className="app-main">
          {page === 'settings' ? (
            <Settings onLogout={onLogout} navigate={navigate} />
          ) : (
            <Dashboard
              usage={usage}
              onUsageChange={loadUsage}
              onTrashChange={loadTrashCount}
              navigate={navigate}
              page={page}
              trashCount={trashCount}
            />
          )}
        </div>

        {/* ═══ TASKBAR ═══ */}
        <div className="taskbar">
          <DropdownMenu.Root open={startOpen} onOpenChange={setStartOpen}>
            <DropdownMenu.Trigger asChild>
              <button className="taskbar-start-btn">
                <span className="taskbar-start-icon">📁</span>
                <span className="taskbar-start-text">Mulai</span>
                <ChevronUp size={12} />
              </button>
            </DropdownMenu.Trigger>
            <DropdownMenu.Portal>
              <DropdownMenu.Content className="start-menu-content" side="top" align="start" sideOffset={8}>
                <div className="start-menu-header">
                  <span style={{ fontSize: 24 }}>📁</span>
                  <div>
                    <div className="font-bold text-sm" style={{ color: '#fff' }}>Syamsu Files</div>
                    <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>{user.username}</div>
                  </div>
                </div>
                <div className="start-menu-body">
                  <DropdownMenu.Item
                    className="start-menu-item"
                    onClick={() => { navigate('/app'); setStartOpen(false); }}
                  >
                    <FolderOpen size={18} /> File Saya
                  </DropdownMenu.Item>
                  <DropdownMenu.Item
                    className="start-menu-item"
                    onClick={() => { navigate('/app/trash'); setStartOpen(false); }}
                  >
                    <Trash2 size={18} />
                    <span className="flex-1">Tempat Sampah</span>
                    {trashCount > 0 && (
                      <span className="badge badge-pink">{trashCount}</span>
                    )}
                  </DropdownMenu.Item>
                  <DropdownMenu.Separator className="start-menu-separator" />
                  <DropdownMenu.Item
                    className="start-menu-item"
                    onClick={() => { navigate('/app/settings'); setStartOpen(false); }}
                  >
                    <SettingsIcon size={18} /> Pengaturan
                  </DropdownMenu.Item>
                  <DropdownMenu.Separator className="start-menu-separator" />
                  <DropdownMenu.Item
                    className="start-menu-item start-menu-item-danger"
                    onClick={() => { onLogout(); setStartOpen(false); }}
                  >
                    <LogOut size={18} /> Keluar
                  </DropdownMenu.Item>
                </div>
              </DropdownMenu.Content>
            </DropdownMenu.Portal>
          </DropdownMenu.Root>

          <div className="taskbar-windows">
            <button
              onClick={() => navigate('/app')}
              className={`taskbar-window-btn ${page === 'dashboard' ? 'active' : ''}`}
            >
              <FolderOpen size={14} />
              <span className="hidden sm:inline">File Saya</span>
            </button>
            {page === 'trash' && (
              <button className="taskbar-window-btn active">
                <Trash2 size={14} />
                <span className="hidden sm:inline">Sampah</span>
              </button>
            )}
            {page === 'settings' && (
              <button className="taskbar-window-btn active">
                <SettingsIcon size={14} />
                <span className="hidden sm:inline">Pengaturan</span>
              </button>
            )}
          </div>

          <div className="taskbar-tray">
            {usage && (
              <div className="taskbar-tray-item hidden md:flex" title={`${usage.usedHuman} / ${usage.quotaHuman} (${usage.percent}%)`}>
                <HardDrive size={13} />
                <div className="progress-track" style={{ width: 50, height: 10, borderWidth: 1.5 }}>
                  <div
                    className="progress-fill"
                    style={{
                      width: `${Math.min(usage.percent, 100)}%`,
                      animation: 'none',
                      background: usage.percent > 90 ? 'var(--danger)' : usage.percent > 70 ? 'var(--warning)' : undefined,
                    }}
                  />
                </div>
                <span style={{ fontSize: 11, fontWeight: 700 }}>{usage.percent}%</span>
              </div>
            )}
            <button
              onClick={toggleTheme}
              className="taskbar-tray-btn"
              title={theme === 'midnight' ? 'Mode Terang' : 'Mode Gelap'}
            >
              {theme === 'midnight' ? <Sun size={16} /> : <Moon size={16} />}
            </button>
            <div className="taskbar-tray-item hidden sm:flex">
              <User size={13} />
              <span style={{ fontSize: 12 }}>{user.username}</span>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

export { navigate };
