import { useState, useEffect } from 'react';
import { Card } from 'primereact/card';
import { useNavigate } from 'react-router-dom';
import Button from '../shared/components/_V2/Button';
import Input from '../shared/components/_V2/InputText';
import { useAuthStore } from '../state/stores/useAuthStore';

interface LoginModalProps {
  redirectUrl?: string;
  onLoginSuccess?: () => void;
}

const LoginModal: React.FC<LoginModalProps> = ({ redirectUrl = '/dashboard', onLoginSuccess }) => {
  const navigate = useNavigate();
  const { login } = useAuthStore();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isTransitioning, setIsTransitioning] = useState(false);

  const handleLogin = async () => {
    setIsTransitioning(true);
    try {
      await login(username, password);
      if (onLoginSuccess) {
        onLoginSuccess();
      }
      navigate(redirectUrl, { replace: true });
    } catch (error) {
      console.error('Login failed:', error);
    } finally {
      setIsTransitioning(false);
    }
  };
  

  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      handleLogin();
    }
  };

  const header = () => <h2 className='text-2xl'>Fusero</h2>;

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      setIsTransitioning(false);
    }, 350);
    return () => clearTimeout(timeoutId);
  }, [isTransitioning]);

  return (
    <div className='flex items-center justify-center w-full h-full overflow-hidden'>
      <Card
        header={header}
        style={{ width: '100%', height: '100%', overflow: 'hidden' }}
        className='flex flex-col items-center justify-center gap-4 p-8 bg-white rounded-md shadowlg'
        
      >
        <div className='w-full'>
          <label htmlFor='username' className='text-sm'>
            Username
          </label>
          <Input
            id='username'
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            className='w-full'
          />
        </div>
        <div className='w-full'>
          <label htmlFor='password' className='text-sm'>
            Password
          </label>
          <Input
            id='password'
            type='password'
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onKeyDown={handleKeyDown}
            className='w-full'
          />
        </div>
        <div className='pt-8'>
          <Button label='Login' className='w-full' onClick={handleLogin} />
        </div>
      </Card>
    </div>
  );
};

export default LoginModal;
