'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod/v4';
import { Loader2, ChevronLeft, User } from 'lucide-react';
import api from '@/lib/api';
import { useAuthStore } from '@/store/auth-store';

const phoneSchema = z.object({
  phone: z.string().regex(/^[6-9]\d{9}$/, 'Enter a valid 10-digit Indian mobile number'),
  name: z.string().min(2, 'Name must be at least 2 characters'),
});
const otpSchema = z.object({
  otp_code: z.string().length(6, 'OTP must be 6 digits'),
});

type PhoneInput = z.infer<typeof phoneSchema>;
type OtpInput = z.infer<typeof otpSchema>;
type Mode = 'phone-name' | 'otp-verify';

export default function RegisterForm() {
  const router = useRouter();
  const { setAuth } = useAuthStore();
  const [mode, setMode] = useState<Mode>('phone-name');
  const [phone, setPhone] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [devOtp, setDevOtp] = useState('');

  const phoneForm = useForm<PhoneInput>({ resolver: zodResolver(phoneSchema) });
  const otpForm   = useForm<OtpInput>({ resolver: zodResolver(otpSchema) });

  const apiError = (err: unknown) =>
    ((err as { response?: { data?: { message?: string } } })?.response?.data?.message) ?? 'Something went wrong.';

  const onSendOtp = async (data: PhoneInput) => {
    setLoading(true); setError(''); setDevOtp('');
    try {
      const res = await api.post('/auth/send-otp', { phone: data.phone, purpose: 'register' });
      setPhone(data.phone);
      if (res.data.otp) setDevOtp(res.data.otp);
      setMode('otp-verify');
    } catch (err) { setError(apiError(err)); }
    finally { setLoading(false); }
  };

  const onVerifyOtp = async (data: OtpInput) => {
    setLoading(true); setError('');
    try {
      const name = phoneForm.getValues('name');
      const res = await api.post('/auth/verify-otp', { phone, otp_code: data.otp_code, purpose: 'register', name });
      setAuth(res.data.data.user, res.data.data.token);
      router.push('/');
    } catch (err) { setError(apiError(err)); }
    finally { setLoading(false); }
  };

  return (
    <div className="w-full max-w-md">
      <div className="relative mt-16 sm:mt-24">
        <Link href="/" className="absolute left-1/2 -translate-x-1/2 -top-16 sm:-top-24 z-10">
          <Image src="/logo-circle.png" alt="Roopaya" width={200} height={200} className="rounded-full shadow-xl ring-[3px] ring-background w-[120px] h-[120px] sm:w-[200px] sm:h-[200px]" />
        </Link>
        <div className="bg-card border border-border rounded-2xl pt-[70px] sm:pt-[110px] pb-6 px-4 sm:px-7 shadow-sm">
          <div className="text-center mb-4">
            <h2 className="font-bold text-[22px] tracking-tight leading-none">Roopaya</h2>
            <p className="text-[9px] font-semibold tracking-[0.25em] uppercase text-primary mt-1">Beauty · Bridal · Couture</p>
          </div>
          <div className="w-10 h-px bg-border mx-auto mb-4" />

        {mode === 'phone-name' && (
          <>
            <h1 className="text-xl font-bold text-center mb-1">Create your account</h1>
            <p className="text-sm text-muted-foreground text-center mb-6">Enter your name and mobile number to get started</p>
            <form onSubmit={phoneForm.handleSubmit(onSendOtp)} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1.5">Full Name</label>
                <div className="relative">
                  <User className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <input {...phoneForm.register('name')} type="text" placeholder="Priya Sharma"
                    className="w-full pl-10 pr-4 py-3 border border-input rounded-xl text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring" />
                </div>
                {phoneForm.formState.errors.name && <p className="text-destructive text-xs mt-1">{phoneForm.formState.errors.name.message}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium mb-1.5">Mobile Number</label>
                <div className="relative">
                  <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-sm text-muted-foreground font-medium">+91</span>
                  <input {...phoneForm.register('phone')} type="tel" placeholder="98765 43210" maxLength={10}
                    className="w-full pl-12 pr-4 py-3 border border-input rounded-xl text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring" />
                </div>
                {phoneForm.formState.errors.phone && <p className="text-destructive text-xs mt-1">{phoneForm.formState.errors.phone.message}</p>}
              </div>
              {error && <p className="text-destructive text-sm bg-destructive/10 px-3 py-2 rounded-lg">{error}</p>}
              <button type="submit" disabled={loading}
                className="w-full flex items-center justify-center gap-2 py-3 bg-primary text-primary-foreground rounded-xl font-semibold hover:opacity-90 disabled:opacity-60 transition-opacity">
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <span>Send OTP</span>}
              </button>
            </form>
            <p className="text-xs text-muted-foreground text-center mt-6">
              Already have an account?{' '}
              <Link href="/login" className="text-primary hover:underline font-medium">Sign in</Link>
            </p>
          </>
        )}

        {mode === 'otp-verify' && (
          <>
            <button onClick={() => { setMode('phone-name'); setError(''); setDevOtp(''); otpForm.reset(); }}
              className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mb-6 transition-colors">
              <ChevronLeft className="w-4 h-4" /> Back
            </button>
            <h1 className="text-xl font-bold mb-1">Verify your number</h1>
            <p className="text-sm text-muted-foreground mb-4">Sent to <span className="font-medium text-foreground">+91 {phone}</span></p>
            {devOtp && (
              <div className="mb-4 px-3 py-2 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-lg">
                <p className="text-xs text-amber-700 dark:text-amber-400 font-medium">Dev mode OTP: <span className="font-mono text-base tracking-widest">{devOtp}</span></p>
              </div>
            )}
            <form onSubmit={otpForm.handleSubmit(onVerifyOtp)} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1.5">6-digit OTP</label>
                <input {...otpForm.register('otp_code')} type="text" inputMode="numeric" placeholder="000000" maxLength={6}
                  className="w-full px-4 py-3 border border-input rounded-xl text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring text-center tracking-[0.5em] text-lg font-bold" />
                {otpForm.formState.errors.otp_code && <p className="text-destructive text-xs mt-1">{otpForm.formState.errors.otp_code.message}</p>}
              </div>
              {error && <p className="text-destructive text-sm bg-destructive/10 px-3 py-2 rounded-lg">{error}</p>}
              <button type="submit" disabled={loading}
                className="w-full flex items-center justify-center gap-2 py-3 bg-primary text-primary-foreground rounded-xl font-semibold hover:opacity-90 disabled:opacity-60 transition-opacity">
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <span>Verify & Create Account</span>}
              </button>
              <button type="button" onClick={() => { setMode('phone-name'); otpForm.reset(); setError(''); setDevOtp(''); }}
                className="w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-1">
                Resend OTP
              </button>
            </form>
          </>
        )}
        </div>
      </div>
    </div>
  );
}
