'use client';

import { Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useAuth } from '../_lib/auth-context';
import { PortalLoginShell } from '../_components/portal-login-shell';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../_components/ui/form';
import { Input } from '../_components/ui/input';
import { Button } from '../_components/ui/button';

const schema = z.object({
  email: z.string().email('Enter a valid email'),
  password: z.string().min(1, 'Password is required'),
});
type FormValues = z.infer<typeof schema>;

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { refresh } = useAuth();
  const next = searchParams.get('next') ?? '/search';

  const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { email: '', password: '' } });

  async function onSubmit(values: FormValues) {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(values),
      credentials: 'include',
    });
    if (!res.ok) {
      const data = await res.json().catch(() => ({})) as { message?: string };
      form.setError('root', { message: data.message ?? 'Invalid email or password' });
      return;
    }
    await refresh();
    router.push(next);
    router.refresh();
  }

  return (
    <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" placeholder="admin@chapter.com" autoComplete="username" {...field} /></FormControl>
            <FormMessage />
          </FormItem>
        )} />
        <FormField control={form.control} name="password" render={({ field }) => (
          <FormItem>
            <FormLabel>Password</FormLabel>
            <FormControl><Input type="password" autoComplete="current-password" {...field} /></FormControl>
            <FormMessage />
          </FormItem>
        )} />
        {form.formState.errors.root && (
          <p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
        )}
        <Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
          {form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
        </Button>
      </form>
    </Form>
  );
}

export default function ChapterLoginPage() {
  return (
    <PortalLoginShell
      title="Chapter Portal"
      subtitle="Sign in to manage your chapter's messages and groups."
      theme="blue"
      highlights={['Approve & route group messages', 'Configure hashtag and prefix rules', 'Review AI-generated digests']}
    >
      <Suspense>
        <LoginForm />
      </Suspense>
    </PortalLoginShell>
  );
}
