import { useState } from 'react';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import type { UserRole } from '@/types';
import { User, Lock, Eye, EyeOff, Loader2 } from 'lucide-react';

const roles: { key: UserRole; label: string }[] = [
  { key: 'admin', label: 'Admin' },
  { key: 'assistant', label: 'Assistant' },
  { key: 'student', label: 'Student' },
];

export default function LoginScreen() {
  const { login, isLoading } = useAuthStore();
  const { showToast } = useUIStore();
  const [role, setRole] = useState<UserRole>('admin');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [shake, setShake] = useState(false);

  const handleLogin = async () => {
    if (!username || !password) {
      showToast({ type: 'error', message: 'Please fill in all fields' });
      return;
    }
    const success = await login(role, username, password);
    if (!success) {
      setShake(true);
      setTimeout(() => setShake(false), 400);
      showToast({ type: 'error', message: 'Invalid credentials. Try: admin/admin123' });
    }
  };

  const fillDemo = (r: UserRole) => {
    setRole(r);
    setUsername(r);
    setPassword(`${r}123`);
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center px-6 py-10">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <img src="/logo.jpg" alt="Logo" className="w-20 h-auto mx-auto rounded-xl shadow-lg mb-4" />
          <h1 className="text-2xl font-bold text-gray-900">SkatePro Academy</h1>
          <p className="text-sm text-gray-500 mt-1">Academy Management System</p>
        </div>

        {/* Role Selector */}
        <div className="flex bg-white rounded-full p-1 border border-gray-200 mb-6 shadow-sm">
          {roles.map((r) => (
            <button
              key={r.key}
              onClick={() => fillDemo(r.key)}
              className={`flex-1 py-2.5 text-sm font-medium rounded-full transition-all duration-200 ${
                role === r.key
                  ? 'brand-gradient text-white shadow-md'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {r.label}
            </button>
          ))}
        </div>

        {/* Form */}
        <div className={`space-y-4 ${shake ? 'animate-[shake_0.4s_ease-in-out]' : ''}`}>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Username</label>
            <div className="relative">
              <User className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text" value={username} onChange={e => setUsername(e.target.value)}
                placeholder="Enter username"
                className="w-full h-12 pl-11 pr-4 bg-white border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15 transition-all"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide">Password</label>
            <div className="relative">
              <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type={showPassword ? 'text' : 'password'} value={password} onChange={e => setPassword(e.target.value)}
                placeholder="Enter password"
                className="w-full h-12 pl-11 pr-11 bg-white border border-gray-200 rounded-xl text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15 transition-all"
              />
              <button onClick={() => setShowPassword(!showPassword)} className="absolute right-3.5 top-1/2 -translate-y-1/2">
                {showPassword ? <EyeOff className="w-4 h-4 text-gray-400" /> : <Eye className="w-4 h-4 text-gray-400" />}
              </button>
            </div>
          </div>

          <button
            onClick={handleLogin}
            disabled={isLoading}
            className="w-full h-12 brand-gradient text-white font-semibold rounded-xl button-shadow flex items-center justify-center gap-2 active:scale-[0.98] transition-transform disabled:opacity-70"
          >
            {isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Log In'}
          </button>
        </div>

        <p className="text-center text-xs text-gray-400 mt-8">v1.0.0</p>
      </div>

      <style>{`
        @keyframes shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-10px); }
          50% { transform: translateX(10px); }
          75% { transform: translateX(-10px); }
        }
      `}</style>
    </div>
  );
}
