import React, { useContext, useState } from 'react';
import './styles.sass';
import Input from '@/common/components/Input';
import Button from '@/common/components/Button';
import { UserContext } from '@/common/contexts/UserContext.jsx';
import { request } from '@/common/utils/RequestUtil.js';
import { LockIcon, UserIcon } from '@phosphor-icons/react';

export const Login = () => {
  const { updateSessionToken, isSetupCompleted } = useContext(UserContext);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [mode, setMode] = useState(isSetupCompleted ? 'login' : 'setup');

  React.useEffect(()=>{
    setMode(isSetupCompleted ? 'login' : 'setup');
  }, [isSetupCompleted]);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      if (mode === 'login') {
        const data = await request('/auth/login','POST',{username, password});
        updateSessionToken(data.token);
      } else { // setup
        await request('/setup/init','POST',{username, password});
        const data = await request('/auth/login','POST',{username, password});
        updateSessionToken(data.token);
      }
    } catch (err) {
      setError(err.error || err.message || 'Error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-wrapper">
      <div className="auth-box">
        <div className="auth-title">{mode === 'login' ? 'Sign in' : 'Initial Setup'}</div>
        <form className="form" onSubmit={submit}>
          <Input label="Username" placeholder="your name" value={username} onChange={e=>setUsername(e.target.value)} icon={<UserIcon size={16} />} autoFocus required />
          <Input type="password" label="Password" placeholder="••••••••" value={password} onChange={e=>setPassword(e.target.value)} icon={<LockIcon size={16} />} required />
          {error && <div style={{color:'#dc3545', fontSize:'.65rem', fontWeight:600}}>{error}</div>}
          <Button type="submit" loading={loading} variant="primary" full>{mode === 'login' ? 'Login' : 'Create Admin & Continue'}</Button>
        </form>
      </div>
    </div>
  );
};