import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useMutation } from "@tanstack/react-query";
import { Search, Settings, User, Sun, Moon, Monitor, Globe } from "lucide-react";
import MainContent from "@/components/MainContent";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export default function Landing() {
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [showRequestModal, setShowRequestModal] = useState(false);
  const [loginForm, setLoginForm] = useState({ username: "", password: "" });
  const [requestForm, setRequestForm] = useState({
    name: "",
    category: "people",
    description: ""
  });
  const { toast } = useToast();
  
  const [theme, setTheme] = useState(() => localStorage.getItem('theme') || 'light');
  const [language, setLanguage] = useState(() => localStorage.getItem('language') || 'en');

  useEffect(() => {
    if (theme === 'dark') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
    localStorage.setItem('theme', theme);
  }, [theme]);

  useEffect(() => {
    localStorage.setItem('language', language);
  }, [language]);

  const handleThemeChange = (newTheme: string) => {
    setTheme(newTheme);
  };

  const handleLanguageChange = (newLanguage: string) => {
    setLanguage(newLanguage);
  };

  const languages = [
    { code: 'en', name: 'English' },
    { code: 'fr', name: 'Français' },
    { code: 'de', name: 'Deutsch' },
    { code: 'it', name: 'Italiano' },
    { code: 'hi', name: 'हिन्दी' },
    { code: 'ar', name: 'العربية' },
    { code: 'ja', name: '日本語' },
    { code: 'ko', name: '한국어' },
    { code: 'zh-TW', name: '繁體中文' },
    { code: 'zh-CN', name: '简体中文' },
  ];

  const loginMutation = useMutation({
    mutationFn: async (credentials: { username: string; password: string }) => {
      return await apiRequest("POST", "/api/login", credentials);
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Successfully logged in!",
      });
      setShowLoginModal(false);
      setLoginForm({ username: "", password: "" });
      // Refresh user data
      queryClient.invalidateQueries({ queryKey: ["/api/auth/user"] });
      // Redirect to home
      window.location.href = "/";
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Invalid credentials. Please try again.",
        variant: "destructive"
      });
    }
  });

  const requestMutation = useMutation({
    mutationFn: async (data: typeof requestForm) => {
      await apiRequest("POST", "/api/media-outlet-requests", data);
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Your media outlet request has been submitted for review.",
      });
      setShowRequestModal(false);
      setRequestForm({ name: "", category: "people", description: "" });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to submit request. Please try again.",
        variant: "destructive"
      });
    }
  });

  const handleLogin = () => {
    setShowLoginModal(true);
  };

  const handleLoginSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    loginMutation.mutate(loginForm);
  };

  const handleRequestSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    requestMutation.mutate(requestForm);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <img 
                src="/attached_assets/검은색 로고_1760521542271.png" 
                alt="SAPIENS" 
                className="h-6 w-auto"
                data-testid="logo-sapiens"
              />
            </div>
            
            <div className="flex items-center space-x-4">
              <div 
                className="relative cursor-pointer flex items-center"
                data-testid="search-container"
              >
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
                <div className="pl-10 pr-16 py-1.5 bg-gray-50 border border-gray-200 rounded-md flex items-center space-x-2 hover:bg-gray-100 transition-colors">
                  <span className="text-sm text-gray-500">search in</span>
                  <img 
                    src="/attached_assets/검은색 로고_1760521542271.png" 
                    alt="SAPIENS" 
                    className="h-2 w-auto"
                  />
                </div>
              </div>
              
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => window.location.href = "/auctions"}
                data-testid="button-auctions"
              >
                Auctions
              </Button>
              
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button 
                    variant="ghost" 
                    size="sm"
                    data-testid="button-settings"
                  >
                    <Settings className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56">
                  <DropdownMenuLabel>Theme</DropdownMenuLabel>
                  <DropdownMenuItem 
                    onClick={() => handleThemeChange('light')}
                    className="cursor-pointer"
                    data-testid="theme-light"
                  >
                    <Sun className="h-4 w-4 mr-2" />
                    Light
                  </DropdownMenuItem>
                  <DropdownMenuItem 
                    onClick={() => handleThemeChange('dark')}
                    className="cursor-pointer"
                    data-testid="theme-dark"
                  >
                    <Moon className="h-4 w-4 mr-2" />
                    Dark
                  </DropdownMenuItem>
                  <DropdownMenuItem 
                    onClick={() => handleThemeChange('system')}
                    className="cursor-pointer"
                    data-testid="theme-system"
                  >
                    <Monitor className="h-4 w-4 mr-2" />
                    System
                  </DropdownMenuItem>
                  
                  <DropdownMenuSeparator />
                  
                  <DropdownMenuLabel>Language</DropdownMenuLabel>
                  {languages.map((lang) => (
                    <DropdownMenuItem 
                      key={lang.code}
                      onClick={() => handleLanguageChange(lang.code)}
                      className="cursor-pointer"
                      data-testid={`language-${lang.code}`}
                    >
                      <Globe className="h-4 w-4 mr-2" />
                      {lang.name}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
              
              <Button 
                variant="ghost" 
                size="sm"
                onClick={handleLogin}
                data-testid="button-login"
              >
                <User className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <MainContent />

      {/* Login Modal */}
      <Dialog open={showLoginModal} onOpenChange={setShowLoginModal}>
        <DialogContent className="sm:max-w-md" data-testid="modal-login">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <span>Login to</span>
              <img 
                src="/attached_assets/Logo_main_1760515844283.png" 
                alt="SAPIENS" 
                className="h-4 w-auto"
              />
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleLoginSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">Username</label>
              <Input
                value={loginForm.username}
                onChange={(e) => setLoginForm(prev => ({ ...prev, username: e.target.value }))}
                onInvalid={(e) => (e.target as HTMLInputElement).setCustomValidity('Please enter your username')}
                onInput={(e) => (e.target as HTMLInputElement).setCustomValidity('')}
                placeholder="Enter username"
                required
                data-testid="input-username"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium mb-2">Password</label>
              <Input
                type="password"
                value={loginForm.password}
                onChange={(e) => setLoginForm(prev => ({ ...prev, password: e.target.value }))}
                onInvalid={(e) => (e.target as HTMLInputElement).setCustomValidity('Please enter your password')}
                onInput={(e) => (e.target as HTMLInputElement).setCustomValidity('')}
                placeholder="Enter password"
                required
                data-testid="input-password"
              />
            </div>
            
            <div className="text-xs text-muted-foreground">
              Use: admin/1234 or superadmin/1234
            </div>
            
            <div className="flex space-x-2">
              <Button 
                type="submit" 
                disabled={loginMutation.isPending}
                className="flex-1"
                data-testid="button-submit-login"
              >
                {loginMutation.isPending ? "Logging in..." : "Login"}
              </Button>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setShowLoginModal(false)}
                data-testid="button-cancel-login"
              >
                Cancel
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* Request Modal */}
      <Dialog open={showRequestModal} onOpenChange={setShowRequestModal}>
        <DialogContent data-testid="modal-request">
          <DialogHeader>
            <DialogTitle>Request New Media Outlet</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleRequestSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">Name</label>
              <Input
                value={requestForm.name}
                onChange={(e) => setRequestForm(prev => ({ ...prev, name: e.target.value }))}
                onInvalid={(e) => (e.target as HTMLInputElement).setCustomValidity('Please enter outlet name')}
                onInput={(e) => (e.target as HTMLInputElement).setCustomValidity('')}
                placeholder="Enter outlet name"
                required
                data-testid="input-outlet-name"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium mb-2">Category</label>
              <select
                value={requestForm.category}
                onChange={(e) => setRequestForm(prev => ({ ...prev, category: e.target.value }))}
                className="w-full px-3 py-2 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-ring"
                data-testid="select-category"
              >
                <option value="people">People</option>
                <option value="topics">Topics</option>
                <option value="companies">Companies</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium mb-2">Description</label>
              <textarea
                value={requestForm.description}
                onChange={(e) => setRequestForm(prev => ({ ...prev, description: e.target.value }))}
                placeholder="Describe why this outlet should be added"
                className="w-full px-3 py-2 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-ring"
                rows={3}
                data-testid="textarea-description"
              />
            </div>
            
            <div className="flex space-x-2">
              <Button 
                type="submit" 
                disabled={requestMutation.isPending}
                data-testid="button-submit-request"
              >
                {requestMutation.isPending ? "Submitting..." : "Submit Request"}
              </Button>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setShowRequestModal(false)}
                data-testid="button-cancel-request"
              >
                Cancel
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
