import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useAuthStore } from '@/auth';
import { Button } from '@/ui/primitives/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/primitives/card';
import { Alert, AlertDescription } from '@/ui/primitives/alert';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/ui/primitives/form';
import { Input } from '@/ui/primitives/input';

const LoginFormSchema = z.object({
  email: z.string().email({ message: 'Enter a valid email address.' }),
  password: z.string().min(1, { message: 'Password is required.' }),
});

type LoginForm = z.infer<typeof LoginFormSchema>;

/**
 * Dev-only prefill from `VITE_ADMIN_EMAIL` / `VITE_ADMIN_PASSWORD`.
 * Production builds get empty strings regardless of build-time env values.
 */
const devDefaults = import.meta.env.DEV
  ? {
      email: import.meta.env.VITE_ADMIN_EMAIL ?? '',
      password: import.meta.env.VITE_ADMIN_PASSWORD ?? '',
    }
  : { email: '', password: '' };

export type LoginPageProps = {
  /** Called once the auth store transitions to `'authenticated'`. */
  onAuthenticated?: () => void;
};

export function LoginPage({ onAuthenticated }: LoginPageProps) {
  const status = useAuthStore((s) => s.status);
  const isSubmitting = status === 'authenticating';
  const [submitError, setSubmitError] = useState<string | null>(null);

  const form = useForm<LoginForm>({
    resolver: zodResolver(LoginFormSchema),
    defaultValues: devDefaults,
  });

  // If the auth store flips to authenticated (e.g. login succeeds, or another
  // tab logs in concurrently), notify the surrounding container.
  useEffect(() => {
    if (status === 'authenticated') {
      onAuthenticated?.();
    }
  }, [status, onAuthenticated]);

  async function onSubmit(values: LoginForm) {
    setSubmitError(null);
    const result = await useAuthStore.getState().login(values.email, values.password);
    if (!result.ok) {
      setSubmitError(result.error);
    }
    // Success path is handled by the status effect above.
  }

  return (
    <div className="min-h-screen grid place-items-center bg-muted p-4">
      <Card className="w-full max-w-sm">
        <CardHeader>
          <CardTitle>Sign in to TRM</CardTitle>
          <CardDescription>Use your operator credentials.</CardDescription>
        </CardHeader>
        <CardContent>
          {submitError && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>{submitError}</AlertDescription>
            </Alert>
          )}
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email</FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        autoComplete="username"
                        autoFocus
                        disabled={isSubmitting}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Password</FormLabel>
                    <FormControl>
                      <Input
                        type="password"
                        autoComplete="current-password"
                        disabled={isSubmitting}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button type="submit" className="w-full" disabled={isSubmitting}>
                {isSubmitting ? 'Signing in…' : 'Sign in'}
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}
