'use client';

import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useOrgAdmin } from '../../_lib/org-admin-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>;

export default function OrgLoginPage() {
  const { login } = useOrgAdmin();
  const router = useRouter();

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

  async function onSubmit(values: FormValues) {
    try {
      await login(values.email, values.password);
      router.replace('/org');
    } catch (err) {
      form.setError('root', { message: err instanceof Error ? err.message : 'Login failed' });
    }
  }

  return (
    <PortalLoginShell
      title="Organisation Portal"
      subtitle="Manage your chapters, admins and org-wide rules."
      theme="violet"
      highlights={['Create and oversee chapters', 'Set org-wide routing rules', 'Provision chapter admins']}
    >
      <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@org.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>
    </PortalLoginShell>
  );
}
