import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useApp } from '../store/AppContext';
import Card from '../components/ui/Card';
import Input from '../components/ui/Input';
import Select from '../components/ui/Select';
import Button from '../components/ui/Button';

const Login = () => {
  const { state, login } = useApp();
  const navigate = useNavigate();
  
  const [selectedUser, setSelectedUser] = useState('');
  const [pin, setPin] = useState('');
  const [error, setError] = useState('');

  const userOptions = [
    { value: '', label: 'Select a user...' },
    ...state.users.map(u => ({ value: u.id, label: u.name }))
  ];

  const handleLogin = (e) => {
    e.preventDefault();
    setError('');
    
    if (!selectedUser || !pin) {
      setError('Please fill in all fields.');
      return;
    }

    const success = login(selectedUser, pin);
    if (success) {
      navigate('/');
    } else {
      setError('Incorrect PIN.');
    }
  };

  return (
    <div className="min-h-screen bg-bg flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <img src="/images/icon.png" alt="Respellion Icon" className="h-24 mx-auto mb-4" />
          <h2 className="text-2xl text-teal font-bold tracking-tight">Respellion</h2>
          <p className="text-fg-muted mt-2">Learning Platform</p>
        </div>

        <Card className="border border-bg-warm">
          <form onSubmit={handleLogin} className="flex flex-col gap-5">
            <Select 
              label="User"
              options={userOptions}
              value={selectedUser}
              onChange={(e) => setSelectedUser(e.target.value)}
            />
            
            <Input 
              label="PIN Code"
              type="password"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={4}
              placeholder="••••"
              value={pin}
              onChange={(e) => setPin(e.target.value)}
            />

            {error && <div className="text-red-500 text-sm font-medium">{error}</div>}

            <Button type="submit" className="mt-2 w-full">
              Sign In
            </Button>
          </form>
        </Card>
      </div>
    </div>
  );
};

export default Login;
