'use client';

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 { 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';
import Link from 'next/link';

const phoneSchema = z.object({ phone: z.string().min(8, 'Enter your WhatsApp number') });
const otpSchema = z.object({ code: z.string().length(6, 'Enter the 6-digit code') });
type PhoneValues = z.infer<typeof phoneSchema>;
type OtpValues = z.infer<typeof otpSchema>;

export default function MemberLoginPage() {
  const router = useRouter();
  const [step, setStep] = useState<'phone' | 'otp'>('phone');
  const [phone, setPhone] = useState('');
  const [challengeId, setChallengeId] = useState('');

  const phoneForm = useForm<PhoneValues>({ resolver: zodResolver(phoneSchema), defaultValues: { phone: '' } });
  const otpForm = useForm<OtpValues>({ resolver: zodResolver(otpSchema), defaultValues: { code: '' } });

  async function onPhone(values: PhoneValues) {
    const res = await fetch('/api/auth/member/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ phone: values.phone }),
    });
    const data = await res.json().catch(() => ({})) as { challengeId?: string; message?: string };
    if (!res.ok) { phoneForm.setError('root', { message: data.message ?? 'Failed to send code' }); return; }
    setPhone(values.phone);
    setChallengeId(data.challengeId ?? '');
    setStep('otp');
  }

  async function onOtp(values: OtpValues) {
    const res = await fetch('/api/my/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ challengeId, phone, code: values.code }),
    });
    const data = await res.json().catch(() => ({})) as { message?: string };
    if (!res.ok) { otpForm.setError('root', { message: data.message ?? 'Verification failed' }); return; }
    router.push('/my');
  }

  return (
    <PortalLoginShell
      title="Member Portal"
      subtitle={step === 'phone' ? 'Enter your WhatsApp number to receive a sign-in code.' : `We sent a 6-digit code to ${phone} on WhatsApp.`}
      theme="emerald"
      highlights={['Read your community digests', 'Manage privacy & consent', 'Discover events and members']}
      footer={
        step === 'phone'
          ? <Link href="/onboard" className="text-emerald-600 hover:underline">First time? Use your invite link</Link>
          : undefined
      }
    >
      {step === 'phone' ? (
        <Form {...phoneForm}>
          <form onSubmit={phoneForm.handleSubmit(onPhone)} className="space-y-4">
            <FormField control={phoneForm.control} name="phone" render={({ field }) => (
              <FormItem>
                <FormLabel>WhatsApp number</FormLabel>
                <FormControl><Input type="tel" placeholder="+91 98765 43210" autoFocus {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />
            {phoneForm.formState.errors.root && (
              <p className="text-sm text-destructive">{phoneForm.formState.errors.root.message}</p>
            )}
            <Button type="submit" className="w-full" disabled={phoneForm.formState.isSubmitting}>
              {phoneForm.formState.isSubmitting ? 'Sending…' : 'Send code'}
            </Button>
          </form>
        </Form>
      ) : (
        <Form {...otpForm}>
          <form onSubmit={otpForm.handleSubmit(onOtp)} className="space-y-4">
            <FormField control={otpForm.control} name="code" render={({ field }) => (
              <FormItem>
                <FormLabel>6-digit code</FormLabel>
                <FormControl>
                  <Input
                    inputMode="numeric"
                    pattern="[0-9]{6}"
                    maxLength={6}
                    placeholder="000000"
                    className="text-center text-xl tracking-[0.5em] font-mono"
                    autoFocus
                    {...field}
                    onChange={(e) => field.onChange(e.target.value.replace(/\D/g, ''))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )} />
            {otpForm.formState.errors.root && (
              <p className="text-sm text-destructive">{otpForm.formState.errors.root.message}</p>
            )}
            <div className="flex gap-2">
              <Button type="button" variant="outline" onClick={() => { setStep('phone'); otpForm.reset(); }} className="flex-none">
                Back
              </Button>
              <Button type="submit" className="flex-1" disabled={otpForm.formState.isSubmitting}>
                {otpForm.formState.isSubmitting ? 'Verifying…' : 'Sign in'}
              </Button>
            </div>
            <Button type="button" variant="ghost" size="sm" className="w-full text-muted-foreground" onClick={() => void onPhone({ phone })}>
              Resend code
            </Button>
          </form>
        </Form>
      )}
    </PortalLoginShell>
  );
}
