
import React, { useState } from 'react';
import { useAuthStore } from '../store/useAuthStore';
import { useUIStore } from '../store/useUIStore';
import { useNavigate } from 'react-router-dom';
import Input from '../components/common/Input';
import Button from '../components/common/Button';
import { Eye, EyeOff, LogIn, ShieldCheck, Sun, Moon } from 'lucide-react';
import { APP_CONFIG } from '../utils/config';

const Login: React.FC = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  
  const { login } = useAuthStore();
  const { addNotification, isDarkMode, toggleTheme } = useUIStore();
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!email || !password) {
      addNotification('error', 'Vui lòng nhập đầy đủ email và mật khẩu');
      return;
    }

    setIsLoading(true);
    try {
      await login(email, password);
      addNotification('success', 'Đăng nhập thành công');
      navigate('/');
    } catch (error: any) {
      // Show specific error message from API if available
      const errorMessage = error.message || 'Đăng nhập thất bại. Vui lòng kiểm tra lại thông tin.';
      addNotification('error', errorMessage);
      console.error('Login error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex bg-slate-50 dark:bg-slate-900 transition-colors duration-300">
      {/* Left Side - Image & Branding */}
      <div className="hidden lg:flex w-1/2 bg-blue-900 relative overflow-hidden items-center justify-center">
        {/* Background Overlay Image */}
        <div 
          className="absolute inset-0 opacity-40 bg-cover bg-center"
          style={{ backgroundImage: "url('https://images.unsplash.com/photo-1509391366360-2e959784a276?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80')" }}
        ></div>
        
        {/* Gradient Overlay */}
        <div className="absolute inset-0 bg-gradient-to-tr from-blue-900 via-blue-900/80 to-transparent"></div>

        {/* Content */}
        <div className="relative z-10 p-12 text-white max-w-xl">
          <div className="mb-8 flex items-center gap-3">
             <div className="p-3 bg-white/10 rounded-xl backdrop-blur-sm border border-white/20">
                <ShieldCheck size={40} className="text-blue-300" />
             </div>
             <h1 className="text-4xl font-bold tracking-tight">VPEG AM & O&M</h1>
          </div>
          <h2 className="text-3xl font-bold mb-6">Hệ thống Quản lý Tài sản & Vận hành Toàn diện</h2>
          <p className="text-blue-100 text-lg leading-relaxed mb-8">
            Tối ưu hóa hiệu suất năng lượng, giám sát thời gian thực và quản lý quy trình bảo trì chuyên nghiệp theo tiêu chuẩn quốc tế.
          </p>
          <div className="flex gap-4 text-sm font-medium text-blue-200">
             <span className="px-3 py-1 bg-white/10 rounded-full border border-white/10">ISO 9001</span>
             <span className="px-3 py-1 bg-white/10 rounded-full border border-white/10">ISO 14001</span>
             <span className="px-3 py-1 bg-white/10 rounded-full border border-white/10">ISO 45001</span>
          </div>
          <div className="mt-12 text-xs text-blue-300">
             © {new Date().getFullYear()} Vũ Phong Energy Group. All rights reserved.
          </div>
        </div>
      </div>

      {/* Right Side - Login Form */}
      <div className="w-full lg:w-1/2 flex flex-col justify-center items-center p-6 sm:p-12 relative">
        {/* Theme Toggle */}
        <button 
          onClick={toggleTheme}
          className="absolute top-6 right-6 p-2 rounded-full text-slate-500 hover:bg-slate-200 dark:hover:bg-slate-800 transition-colors"
        >
          {isDarkMode ? <Sun size={20} /> : <Moon size={20} />}
        </button>

        <div className="w-full max-w-md space-y-8">
          <div className="text-center lg:text-left">
            <div className="flex justify-center lg:justify-start lg:hidden mb-4">
               <ShieldCheck size={48} className="text-blue-600 dark:text-blue-500" />
            </div>
            <h2 className="text-3xl font-bold text-slate-900 dark:text-white">Chào mừng trở lại</h2>
            <p className="mt-2 text-sm text-slate-600 dark:text-slate-400">
              Vui lòng đăng nhập để truy cập hệ thống quản trị.
            </p>
          </div>


          <form className="mt-8 space-y-6" onSubmit={handleLogin}>
            <div className="space-y-5">
              <Input
                id="email"
                type="email"
                label="Email doanh nghiệp"
                placeholder="name@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoComplete="email"
                required
              />
              
              <div className="space-y-1">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  label="Mật khẩu"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="current-password"
                  required
                  rightIcon={showPassword ? <EyeOff size={18}/> : <Eye size={18}/>}
                  onRightIconClick={() => setShowPassword(!showPassword)}
                />
                <div className="flex items-center justify-between">
                  <div className="flex items-center">
                    <input
                      id="remember-me"
                      name="remember-me"
                      type="checkbox"
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 rounded cursor-pointer"
                    />
                    <label htmlFor="remember-me" className="ml-2 block text-sm text-slate-700 dark:text-slate-300 cursor-pointer">
                      Ghi nhớ đăng nhập
                    </label>
                  </div>
                  <div className="text-sm">
                    <a href="#" className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300">
                      Quên mật khẩu?
                    </a>
                  </div>
                </div>
              </div>
            </div>

            <Button
              type="submit"
              variant="primary"
              size="lg"
              className="w-full shadow-lg shadow-blue-500/30"
              isLoading={isLoading}
              icon={<LogIn size={18} />}
            >
              Đăng nhập
            </Button>
          </form>

          <div className="mt-6 text-center text-xs text-slate-500 dark:text-slate-400">
             Phiên bản {APP_CONFIG.APP_VERSION} • {APP_CONFIG.ENV} Mode
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
