'use client';

/**
 * Login Page
 * User authentication page with username/password and PIN login
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useAuth } from '@/contexts/AuthContext';
import { Button, Input, Card, CardHeader, CardTitle, CardContent } from '@/components/ui';
import { LoadingSpinner } from '@/components/ui';
import toast from 'react-hot-toast';

// Validation schema
const loginSchema = z.object({
  username: z.string().min(1, 'Username is required'),
  password: z.string().min(1, 'Password is required'),
});

const pinSchema = z.object({
  username: z.string().min(1, 'Username is required'),
  pinCode: z.string().min(4, 'PIN must be at least 4 digits').max(6, 'PIN must be at most 6 digits'),
});

export default function LoginPage() {
  const router = useRouter();
  const { login, loginWithPin } = useAuth();
  const [loginMode, setLoginMode] = useState('password'); // 'password' or 'pin'
  const [isLoading, setIsLoading] = useState(false);

  // Password login form
  const {
    register: registerPassword,
    handleSubmit: handleSubmitPassword,
    formState: { errors: passwordErrors },
  } = useForm({
    resolver: zodResolver(loginSchema),
  });

  // PIN login form
  const {
    register: registerPin,
    handleSubmit: handleSubmitPin,
    formState: { errors: pinErrors },
  } = useForm({
    resolver: zodResolver(pinSchema),
  });

  // Handle password login
  const onPasswordSubmit = async (data) => {
    setIsLoading(true);
    try {
      const result = await login(data.username, data.password);
      
      if (result.success) {
        toast.success('Login successful!');
        router.push('/');
      } else {
        toast.error(result.error || 'Login failed. Please check your credentials.');
      }
    } catch (error) {
      toast.error('An error occurred. Please try again.');
      console.error('Login error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // Handle PIN login
  const onPinSubmit = async (data) => {
    setIsLoading(true);
    try {
      const result = await loginWithPin(data.username, data.pinCode);
      
      if (result.success) {
        toast.success('Login successful!');
        router.push('/');
      } else {
        toast.error(result.error || 'PIN login failed. Please check your PIN.');
      }
    } catch (error) {
      toast.error('An error occurred. Please try again.');
      console.error('PIN login error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        {/* Logo/Title */}
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white">XYZ POS</h1>
          <p className="mt-2 text-gray-600 dark:text-gray-400">Point of Sale System</p>
        </div>

        {/* Login Card */}
        <Card>
          <CardHeader>
            <CardTitle>Sign in to your account</CardTitle>
          </CardHeader>
          <CardContent>
            {/* Toggle between Password and PIN */}
            <div className="flex space-x-2 mb-6">
              <button
                onClick={() => setLoginMode('password')}
                className={`flex-1 py-2 px-4 rounded-lg font-medium transition-colors ${
                  loginMode === 'password'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
                }`}
              >
                Username
              </button>
              <button
                onClick={() => setLoginMode('pin')}
                className={`flex-1 py-2 px-4 rounded-lg font-medium transition-colors ${
                  loginMode === 'pin'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
                }`}
              >
                PIN
              </button>
            </div>

            {/* Password Login Form */}
            {loginMode === 'password' && (
              <form onSubmit={handleSubmitPassword(onPasswordSubmit)} className="space-y-4">
                <Input
                  label="Username"
                  type="text"
                  placeholder="Enter your username"
                  {...registerPassword('username')}
                  error={passwordErrors.username?.message}
                  disabled={isLoading}
                  autoFocus
                />

                <Input
                  label="Password"
                  type="password"
                  placeholder="Enter your password"
                  {...registerPassword('password')}
                  error={passwordErrors.password?.message}
                  disabled={isLoading}
                />

                <Button
                  type="submit"
                  variant="primary"
                  className="w-full"
                  disabled={isLoading}
                  loading={isLoading}
                >
                  Sign In
                </Button>
              </form>
            )}

            {/* PIN Login Form */}
            {loginMode === 'pin' && (
              <form onSubmit={handleSubmitPin(onPinSubmit)} className="space-y-4">
                <Input
                  label="Username"
                  type="text"
                  placeholder="Enter your username"
                  {...registerPin('username')}
                  error={pinErrors.username?.message}
                  disabled={isLoading}
                  autoFocus
                />
                <Input
                  label="PIN Code"
                  type="password"
                  placeholder="Enter 4-6 digit PIN"
                  maxLength={6}
                  {...registerPin('pinCode')}
                  error={pinErrors.pinCode?.message}
                  disabled={isLoading}
                />

                <Button
                  type="submit"
                  variant="primary"
                  className="w-full"
                  disabled={isLoading}
                  loading={isLoading}
                >
                  Sign In with PIN
                </Button>
              </form>
            )}
          </CardContent>
        </Card>

        {/* Footer */}
        <p className="text-center text-sm text-gray-600 dark:text-gray-400">
          Need help? Contact your system administrator
        </p>
      </div>
    </div>
  );
}

