
"use client";

import { useState, useEffect } from 'react'; // Added useEffect
import { useRouter } from 'next/navigation';
import { useForm, type SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
import { auth } from '@/lib/firebase';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { APP_NAME } from '@/constants';
import { LogIn, Chrome } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import Link from 'next/link'; // Added Link import

// If this page were a server component, you could export metadata like this:
// export const metadata: Metadata = {
//   title: `Staff Login | ${APP_NAME}`,
//   description: `Login to the ${APP_NAME} staff portal.`,
//   robots: {
//     index: false,
//     follow: false,
//   },
// };


const loginSchema = z.object({
  email: z.string().email({ message: 'Invalid email address' }),
  password: z.string().min(6, { message: 'Password must be at least 6 characters' }),
});
type LoginFormValues = z.infer<typeof loginSchema>;

export default function StaffLoginPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [googleIsLoading, setGoogleIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
  });

  const handleLogin: SubmitHandler<LoginFormValues> = async (data) => {
    setIsLoading(true);
    try {
      await signInWithEmailAndPassword(auth, data.email, data.password);
      toast({ title: 'Login Successful', description: 'Redirecting to dashboard...' });
      router.push('/staff-portal/dashboard');
    } catch (error: any) {
      console.error('Login error:', error);
      toast({
        title: 'Login Failed',
        description: error.message || 'An unexpected error occurred.',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGoogleSignIn = async () => {
    setGoogleIsLoading(true);
    const provider = new GoogleAuthProvider();
    try {
      await signInWithPopup(auth, provider);
      toast({ title: 'Login Successful', description: 'Redirecting to dashboard...' });
      router.push('/staff-portal/dashboard');
    } catch (error: any) {
      console.error('Google Sign-In error:', error);
       toast({
        title: 'Google Sign-In Failed',
        description: error.message || 'Could not sign in with Google.',
        variant: 'destructive',
      });
    } finally {
      setGoogleIsLoading(false);
    }
  };
  
  // Set document title dynamically for client components
  useEffect(() => { // Changed from useState to useEffect for side effect
    if (typeof window !== 'undefined') {
        document.title = `Staff Login | ${APP_NAME}`;
    }
  }, []);


  return (
    <div className="min-h-screen flex items-center justify-center bg-muted/30 py-12 px-4 sm:px-6 lg:px-8">
      <Card className="w-full max-w-md shadow-xl">
        <CardHeader className="text-center">
          <LogIn className="h-10 w-10 text-primary mx-auto mb-3" />
          <CardTitle className="text-2xl font-bold text-primary text-shadow-primary">Staff Portal Login</CardTitle>
          <CardDescription>Access your {APP_NAME} dashboard.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(handleLogin)} className="space-y-6">
            <div>
              <Label htmlFor="email">Email Address</Label>
              <Input
                id="email"
                type="email"
                {...register('email')}
                className="mt-1"
                placeholder="you@example.com"
                disabled={isLoading || googleIsLoading}
              />
              {errors.email && <p className="text-sm text-destructive mt-1">{errors.email.message}</p>}
            </div>
            <div>
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                {...register('password')}
                className="mt-1"
                placeholder="••••••••"
                disabled={isLoading || googleIsLoading}
              />
              {errors.password && <p className="text-sm text-destructive mt-1">{errors.password.message}</p>}
            </div>
            <Button type="submit" className="w-full text-lg py-3" size="lg" disabled={isLoading || googleIsLoading}>
              {isLoading ? 'Logging in...' : 'Login'}
            </Button>
          </form>
        </CardContent>
        <CardFooter className="flex flex-col gap-4 pt-4">
          <div className="relative w-full">
            <div className="absolute inset-0 flex items-center">
              <span className="w-full border-t" />
            </div>
            <div className="relative flex justify-center text-xs uppercase">
              <span className="bg-card px-2 text-muted-foreground">Or continue with</span>
            </div>
          </div>
          <Button
            variant="outline"
            className="w-full text-md py-2.5"
            onClick={handleGoogleSignIn}
            disabled={isLoading || googleIsLoading}
          >
            {googleIsLoading ? (
              'Signing in...'
            ) : (
              <>
                <Chrome className="mr-2 h-5 w-5" /> Sign in with Google
              </>
            )}
          </Button>
          <p className="text-center text-sm text-muted-foreground">
            Don&apos;t have an account?{' '}
            <Link href="/staff-portal/signup" className="font-medium text-primary hover:underline text-shadow-primary">
              Sign up
            </Link>
          </p>
           <p className="text-center text-sm text-muted-foreground">
             <Link href="/" className="font-medium text-primary hover:underline text-shadow-primary">
              &larr; Back to {APP_NAME} Home
            </Link>
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
