'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../../contexts/AuthContext';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import Image from 'next/image';
import { useTheme } from '../../lib/theme';

export default function LoginPage() {
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { login, isAuthenticated } = useAuth();
  const { theme, toggleTheme } = useTheme();
  const router = useRouter();

  useEffect(() => {
    if (isAuthenticated) {
      router.push('/library');
    }
  }, [isAuthenticated, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      await login(password);
      router.push('/library');
    } catch (err: any) {
      setError(err.response?.data?.message || 'Invalid password');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col justify-center py-12 sm:px-6 lg:px-8 theme-bg">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        {/* Logo */}
        <div className="flex justify-center mb-8">
          <Image
            src={theme === 'dark' ? '/logo-dark-large.png' : '/logo-large.png'}
            alt="StoryCove"
            width={128}
            height={128}
            priority
          />
        </div>
        
        <h1 className="text-center text-3xl font-bold theme-header mb-2">
          Welcome to StoryCove
        </h1>
        <p className="text-center theme-text">
          Enter your password to access your story collection
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="theme-card theme-shadow py-8 px-4 sm:rounded-lg sm:px-10">
          <form onSubmit={handleSubmit} className="space-y-6">
            <Input
              type="password"
              label="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
              required
              autoFocus
              error={error}
            />

            <Button
              type="submit"
              className="w-full"
              loading={loading}
              disabled={!password}
            >
              Sign In
            </Button>
          </form>

          {/* Theme Toggle */}
          <div className="mt-6 flex justify-center">
            <button
              onClick={toggleTheme}
              className="theme-text hover:theme-accent transition-colors"
              aria-label="Toggle theme"
            >
              {theme === 'light' ? '🌙 Dark Mode' : '☀️ Light Mode'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}