'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import api from '@/lib/axios';
import { useAuthStore } from '@/store/auth';
import { Loader2, Gift, User, Phone, Lock, Mail, MapPin, Calendar } from 'lucide-react';
import MathCaptcha from '@/components/MathCaptcha';

const schema = z.object({
  full_name: z.string().min(3, 'Nama minimal 3 karakter'),
  phone: z.string().regex(/^\d+$/, 'Nomor HP hanya boleh angka').min(9, 'Nomor HP tidak valid'),
  otp: z.string().length(6, 'OTP harus 6 digit'),
  password: z.string().min(6, 'Password minimal 6 karakter'),
  password_confirmation: z.string(),
  email: z.string().min(1, 'Email wajib diisi').email('Email tidak valid'),
  address: z.string().optional(),
  birth_date: z.string().optional(),
  terms_accepted: z.boolean().refine(v => v === true, 'Anda harus menyetujui syarat dan ketentuan'),
}).refine((d) => d.password === d.password_confirmation, {
  message: 'Konfirmasi password tidak cocok',
  path: ['password_confirmation'],
});
type FormData = z.infer<typeof schema>;

export default function RegisterPage() {
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuth);
  const [loading, setLoading] = useState(false);
  const [otpSent, setOtpSent] = useState(false);
  const [otpLoading, setOtpLoading] = useState(false);
  const [captchaOk, setCaptchaOk] = useState(false);
  const [captchaKey, setCaptchaKey] = useState(0);

  const { register, handleSubmit, watch, setValue, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { terms_accepted: false },
  });

  const phone = watch('phone');

  const sendOtp = async () => {
    if (!phone || phone.length < 9) { toast.error('Masukkan nomor HP yang valid'); return; }
    setOtpLoading(true);
    try {
      const res = await api.post('/end-user/send-otp', { phone });
      setOtpSent(true);
      if (res.data.otp_debug) {
        setValue('otp', res.data.otp_debug);
        toast.success(`[TEST] OTP: ${res.data.otp_debug}`);
      } else {
        toast.success('OTP telah dikirim via WhatsApp');
      }
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Gagal mengirim OTP');
    } finally {
      setOtpLoading(false);
    }
  };

  const onSubmit = async (data: FormData) => {
    if (!captchaOk) { toast.error('Selesaikan verifikasi CAPTCHA terlebih dahulu.'); return; }
    setLoading(true);
    try {
      const res = await api.post('/end-user/register', data);
      setAuth(res.data.data, res.data.token);
      toast.success('Registrasi berhasil!');
      router.push('/dashboard');
    } catch (err: any) {
      const msg = err.response?.data?.errors
        ? Object.values(err.response.data.errors).flat().join(', ')
        : err.response?.data?.message ?? 'Registrasi gagal';
      toast.error(msg);
      setCaptchaOk(false);
      setCaptchaKey(k => k + 1);
    } finally {
      setLoading(false);
    }
  };

  const inputCls = "w-full h-11 bg-white/20 border border-white/30 rounded-xl px-4 text-sm text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/50 transition";

  return (
    <div className="relative min-h-screen w-full bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-700 flex items-start justify-center px-4 py-8 overflow-y-auto overflow-x-hidden">
      <div className="absolute top-0 right-0 w-80 h-80 bg-white/10 rounded-full blur-3xl translate-x-1/3 -translate-y-1/3 pointer-events-none" />
      <div className="absolute bottom-0 left-0 w-96 h-96 bg-blue-500/20 rounded-full blur-3xl -translate-x-1/3 translate-y-1/3 pointer-events-none" />

      {(loading || otpLoading) && (
        <div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-black/40 backdrop-blur-sm">
          <Loader2 className="w-10 h-10 text-white animate-spin mb-3" />
          <p className="text-sm font-medium text-white">{otpLoading ? 'Mengirim OTP...' : 'Mendaftarkan akun...'}</p>
        </div>
      )}

      <div className="relative w-full max-w-md">
        <div className="text-center mb-6">
          <div className="inline-flex items-center justify-center w-14 h-14 bg-white/20 backdrop-blur-sm rounded-2xl mb-3 shadow-lg">
            <Gift className="w-7 h-7 text-white" />
          </div>
          <h1 className="text-3xl font-extrabold text-white">Daftar Akun</h1>
          <p className="text-white/70 text-sm mt-1">Buat akun BMU baru Anda</p>
        </div>

        <div className="bg-white/15 backdrop-blur-md border border-white/20 rounded-3xl p-7 shadow-2xl text-white">
          {/* Link login di atas form */}
          <p className="text-center text-sm text-white/70 mb-5">
            Sudah punya akun?{' '}
            <Link href="/login" className="text-white font-semibold hover:underline">Masuk</Link>
          </p>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div>
              <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><User className="h-3.5 w-3.5" /> Nama Lengkap</label>
              <input {...register('full_name')} placeholder="Nama lengkap" className={inputCls} autoComplete="off" />
              {errors.full_name && <p className="text-red-300 text-xs mt-1">{errors.full_name.message}</p>}
            </div>

            <div>
              <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><Phone className="h-3.5 w-3.5" /> Nomor HP (WhatsApp)</label>
              
                <input {...register('phone')} type="tel" inputMode="numeric" placeholder="08xxxxxxxxxx"
                  className={inputCls + ' flex-1'}
                  onChange={(e) => { const n = e.target.value.replace(/\D/g, ''); e.target.value = n; register('phone').onChange(e); }} />
                
              
              {errors.phone && <p className="text-red-300 text-xs mt-1">{errors.phone.message}</p>}
            </div>
            

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><Lock className="h-3.5 w-3.5" /> Password</label>
                <input {...register('password')} type="password" placeholder="Min. 6 karakter" className={inputCls} />
                {errors.password && <p className="text-red-300 text-xs mt-1">{errors.password.message}</p>}
              </div>
              <div>
                <label className="text-xs font-medium text-white/80 mb-1 block">Konfirmasi</label>
                <input {...register('password_confirmation')} type="password" placeholder="Ulangi password" className={inputCls} />
                {errors.password_confirmation && <p className="text-red-300 text-xs mt-1">{errors.password_confirmation.message}</p>}
              </div>
            </div>

            <div>
              <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><Mail className="h-3.5 w-3.5" /> Email <span className="text-red-300">*</span></label>
              <input {...register('email')} type="email" placeholder="email@contoh.com" className={inputCls} />
              {errors.email && <p className="text-red-300 text-xs mt-1">{errors.email.message}</p>}
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><MapPin className="h-3.5 w-3.5" /> Alamat</label>
                <textarea {...register('address')} rows={2} placeholder="Alamat (opsional)"
                  className="w-full bg-white/20 border border-white/30 rounded-xl px-4 py-2 text-sm text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/50 transition resize-none" />
              </div>
              <div>
                <label className="flex items-center gap-1.5 text-xs font-medium text-white/80 mb-1"><Calendar className="h-3.5 w-3.5" /> Tgl Lahir</label>
                <input {...register('birth_date')} type="date"
                  className="w-full h-11 bg-white/20 border border-white/30 rounded-xl px-3 text-sm text-white focus:outline-none focus:ring-2 focus:ring-white/50 transition" />
              </div>
            </div>

            <MathCaptcha key={captchaKey} onVerified={setCaptchaOk} />

            
            <div>
              <label className="text-xs font-medium text-white/80 mb-1 block">Kode OTP</label>
              <div className="flex gap-2">
              <button type="button" onClick={sendOtp} disabled={otpLoading}
                  className="px-3 py-2 text-xs bg-white/30 hover:bg-white/50 text-white rounded-xl font-medium disabled:opacity-50 whitespace-nowrap transition">
                  {otpSent ? 'Kirim Ulang' : 'Kirim OTP'}
                </button>
              <input {...register('otp')} placeholder="6 digit OTP dari WhatsApp" maxLength={6} className={inputCls} autoComplete="off" />
              </div>
              {errors.otp && <p className="text-red-300 text-xs mt-1">{errors.otp.message}</p>}
            </div>

            {/* Checkbox T&C */}
            <div className="flex items-start gap-2 bg-white/10 rounded-xl p-3">
              <input {...register('terms_accepted')} type="checkbox" id="terms" className="mt-0.5" />
              <label htmlFor="terms" className="text-xs text-white/90 leading-relaxed">
                Saya sudah membaca dan menyetujui{' '}
                <Link href="/terms" target="_blank" className="text-white font-semibold underline hover:opacity-80">
                  syarat dan ketentuan
                </Link>
              </label>
            </div>
            {errors.terms_accepted && <p className="text-red-300 text-xs -mt-2">{errors.terms_accepted.message}</p>}

            <button type="submit" disabled={loading || !captchaOk}
              className="w-full h-11 bg-white text-teal-700 font-bold rounded-xl shadow-lg hover:bg-white/90 disabled:opacity-50 transition flex items-center justify-center gap-2">
              {loading ? <span className="h-4 w-4 animate-spin rounded-full border-2 border-teal-600 border-t-transparent" /> : <Gift className="h-4 w-4" />}
              {loading ? 'Mendaftar...' : 'Daftar Sekarang'}
            </button>
          </form>
        </div>

        <p className="text-center text-white/50 text-xs mt-5">
          <Link href="/" className="hover:text-white transition">← Kembali ke beranda</Link>
        </p>
      </div>
    </div>
  );
}
