import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Copy, FileCode, Download, Info, Play, FolderPlus, User, SignOut, List, ArrowsLeftRight, UserCircle, GitBranch, Package, Cube } from '@phosphor-icons/react';
import { toast } from 'sonner';
import { useState, useEffect, useCallback, memo } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui/dialog';
import { ThemeSwitcher } from './ThemeSwitcher';
import { PlatformSelector } from './PlatformSelector';
import { PlatformId } from '../lib/platforms';
import { Button } from './ui/button';

interface ToolbarProps {
  code: string;
  onTemplatesClick: () => void;
  onPreviewClick: () => void;
  onNewProjectClick: () => void;
  currentPlatform: PlatformId;
  onPlatformChange: (platform: PlatformId) => void;
  onTranslateClick?: () => void;
  onAvatarToolkitClick?: () => void;
  onVisualScriptingClick?: () => void;
  onAssetLibraryClick?: () => void;
  onLivePreviewClick?: () => void;
}

export function Toolbar({ code, onTemplatesClick, onPreviewClick, onNewProjectClick, currentPlatform, onPlatformChange, onTranslateClick, onAvatarToolkitClick, onVisualScriptingClick, onAssetLibraryClick, onLivePreviewClick }: ToolbarProps) {
  const [showInfo, setShowInfo] = useState(false);
  const [user, setUser] = useState<{ login: string; avatarUrl: string; email: string } | null>(null);

  useEffect(() => {
    if (typeof window !== 'undefined' && window.spark?.user) {
      window.spark.user().then(setUser).catch(() => setUser(null));
    } else {
      setUser(null);
    }
  }, []);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(code);
      toast.success('Code copied to clipboard!');
    } catch (error) {
      toast.error('Failed to copy code');
    }
  }, [code]);

  const handleExport = useCallback(() => {
    const blob = new Blob([code], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'script.lua';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    toast.success('Script exported!');
  }, [code]);

  return (
    <>
      <div className="flex items-center gap-1 px-2 py-1.5 bg-card border-b border-border min-h-[38px] md:min-h-[42px]">
        <h1 className="text-base md:text-lg font-bold tracking-tight leading-none">
          Ae<span className="text-accent">Thex</span>
        </h1>
        <span className="text-xs text-muted-foreground ml-1 leading-none">Studio</span>

        <div className="flex-1" />

        {/* Desktop: Show all buttons */}
        <TooltipProvider>
          <div className="hidden md:flex items-center gap-2">
            {/* Platform Selector */}
            <PlatformSelector
              value={currentPlatform}
              onChange={onPlatformChange}
            />

            {/* Translation Button */}
            {onTranslateClick && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onTranslateClick}
                    className="h-8 px-3 text-xs gap-1"
                    aria-label="Translate Code"
                  >
                    <ArrowsLeftRight size={14} />
                    <span>Translate</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Cross-Platform Translation</TooltipContent>
              </Tooltip>
            )}

            {/* Avatar Toolkit Button */}
            {onAvatarToolkitClick && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onAvatarToolkitClick}
                    className="h-8 px-3 text-xs gap-1"
                    aria-label="Avatar Toolkit"
                  >
                    <UserCircle size={14} />
                    <span>Avatars</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Cross-Platform Avatar Toolkit</TooltipContent>
              </Tooltip>
            )}

            {/* Visual Scripting Button */}
            {onVisualScriptingClick && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onVisualScriptingClick}
                    className="h-8 px-3 text-xs gap-1"
                    aria-label="Visual Scripting"
                  >
                    <GitBranch size={14} />
                    <span>Visual</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Visual Scripting (Node Editor)</TooltipContent>
              </Tooltip>
            )}

            {/* Asset Library Button */}
            {onAssetLibraryClick && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onAssetLibraryClick}
                    className="h-8 px-3 text-xs gap-1"
                    aria-label="Asset Library"
                  >
                    <Package size={14} />
                    <span>Assets</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Asset Library (Models, Textures, Audio)</TooltipContent>
              </Tooltip>
            )}

            {/* Live Preview Button */}
            {onLivePreviewClick && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onLivePreviewClick}
                    className="h-8 px-3 text-xs gap-1 bg-primary/10 border-primary/30 hover:bg-primary/20"
                    aria-label="Live Preview"
                  >
                    <Cube size={14} />
                    <span>3D Preview</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Live 3D Preview with Lua Execution</TooltipContent>
              </Tooltip>
            )}

            <div className="h-6 w-px bg-border mx-1" />

            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={onNewProjectClick}
                  className="p-1.5 rounded hover:bg-accent/10"
                  aria-label="New Project"
                >
                  <FolderPlus size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>New Project</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={onPreviewClick}
                  className="p-1.5 rounded hover:bg-accent/10"
                  aria-label="Preview"
                >
                  <Play size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Preview</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" size="icon" onClick={onTemplatesClick} className="p-1.5 rounded hover:bg-accent/10" aria-label="Templates">
                  <FileCode size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Templates</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" size="icon" onClick={handleCopy} className="p-1.5 rounded hover:bg-accent/10" aria-label="Copy">
                  <Copy size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Copy</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={handleExport}
                  className="p-1.5 rounded hover:bg-accent/10"
                  aria-label="Export"
                >
                  <Download size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Export</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" size="icon" onClick={() => setShowInfo(true)} className="p-1.5 rounded hover:bg-accent/10" aria-label="About">
                  <Info size={18} />
                </Button>
              </TooltipTrigger>
              <TooltipContent>About</TooltipContent>
            </Tooltip>

            <ThemeSwitcher />
          </div>

          {/* Mobile: Hamburger menu with essential actions */}
          <div className="flex md:hidden items-center gap-1">
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={onPreviewClick}
                  className="p-2 rounded hover:bg-accent/10"
                  aria-label="Preview"
                >
                  <Play size={20} weight="bold" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Preview</TooltipContent>
            </Tooltip>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="p-2 rounded hover:bg-accent/10"
                  aria-label="Menu"
                >
                  <List size={20} weight="bold" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem onClick={onNewProjectClick}>
                  <FolderPlus className="mr-2" size={16} />
                  <span>New Project</span>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={onTemplatesClick}>
                  <FileCode className="mr-2" size={16} />
                  <span>Templates</span>
                </DropdownMenuItem>
                {onAvatarToolkitClick && (
                  <DropdownMenuItem onClick={onAvatarToolkitClick}>
                    <UserCircle className="mr-2" size={16} />
                    <span>Avatar Toolkit</span>
                  </DropdownMenuItem>
                )}
                {onVisualScriptingClick && (
                  <DropdownMenuItem onClick={onVisualScriptingClick}>
                    <GitBranch className="mr-2" size={16} />
                    <span>Visual Scripting</span>
                  </DropdownMenuItem>
                )}
                {onAssetLibraryClick && (
                  <DropdownMenuItem onClick={onAssetLibraryClick}>
                    <Package className="mr-2" size={16} />
                    <span>Asset Library</span>
                  </DropdownMenuItem>
                )}
                {onLivePreviewClick && (
                  <DropdownMenuItem onClick={onLivePreviewClick}>
                    <Cube className="mr-2" size={16} />
                    <span>3D Preview</span>
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem onClick={handleCopy}>
                  <Copy className="mr-2" size={16} />
                  <span>Copy Code</span>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={handleExport}>
                  <Download className="mr-2" size={16} />
                  <span>Export</span>
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => setShowInfo(true)}>
                  <Info className="mr-2" size={16} />
                  <span>About</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </TooltipProvider>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="rounded-full p-0 ml-1">
              <Avatar className="h-7 w-7 md:h-8 md:w-8">
                <AvatarImage src={user?.avatarUrl} alt={user?.login || 'User'} />
                <AvatarFallback>
                  <User size={16} />
                </AvatarFallback>
              </Avatar>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {user && (
              <>
                <div className="px-2 py-1.5">
                  <p className="text-xs font-semibold">{user.login}</p>
                  <p className="text-[10px] text-muted-foreground">{user.email}</p>
                </div>
                <DropdownMenuSeparator />
              </>
            )}
            <DropdownMenuItem onClick={() => toast.info('Profile coming soon!')}>
              <User className="mr-2" size={14} />
              <span className="text-xs">Profile</span>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => toast.info('Sign out feature coming soon!')}>
              <SignOut className="mr-2" size={14} />
              <span className="text-xs">Sign Out</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      <Dialog open={showInfo} onOpenChange={setShowInfo}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>About AeThex Studio</DialogTitle>
            <DialogDescription className="space-y-3 pt-2">
              <p>
                AeThex Studio is a browser-based Roblox Lua editor with AI assistance,
                designed to help you write better scripts faster.
              </p>
              <div className="space-y-2 text-sm">
                <div>
                  <strong className="text-foreground">Features:</strong>
                  <ul className="list-disc list-inside mt-1 space-y-1 text-muted-foreground">
                    <li>Monaco editor with Lua syntax highlighting</li>
                    <li>AI assistant for code help and debugging</li>
                    <li>Ready-made script templates</li>
                    <li>Auto-save (code persists between sessions)</li>
                    <li>Export to .lua files</li>
                  </ul>
                </div>
                <div>
                  <strong className="text-foreground">Tips:</strong>
                  <ul className="list-disc list-inside mt-1 space-y-1 text-muted-foreground">
                    <li>Your code is automatically saved as you type</li>
                    <li>Ask the AI assistant about any Roblox API or scripting concepts</li>
                    <li>Use templates as starting points for common tasks</li>
                    <li>Copy your finished scripts to paste into Roblox Studio</li>
                  </ul>
                </div>
              </div>
            </DialogDescription>
          </DialogHeader>
        </DialogContent>
      </Dialog>
    </>
  );
}
