'use client';

import React, { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, User, Smartphone, Lock, Check } from 'lucide-react';
import { apiRequest, setCurrentUser } from '../../../lib/api';
import { Button } from '../../../components/Button';
import { AuthShell, AuthField, AuthError } from '../../../components/AuthShell';

type Step = 'details' | 'otp';

export default function RegisterPage() {
  const router = useRouter();
  const [step, setStep] = useState<Step>('details');
  const [form, setForm] = useState({ name: '', phone: '', password: '', confirm: '' });
  const [otp, setOtp] = useState(['', '', '', '', '', '']);
  const [showPw, setShowPw] = useState(false);
  const [agree, setAgree] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [devHint, setDevHint] = useState('');
  const [cooldown, setCooldown] = useState(0);
  const otpRefs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    if (cooldown <= 0) return;
    const t = setTimeout(() => setCooldown(cooldown - 1), 1000);
    return () => clearTimeout(t);
  }, [cooldown]);

  const strength = useMemo(() => {
    const p = form.password;
    let s = 0;
    if (p.length >= 8) s++;
    if (/[A-Z]/.test(p)) s++;
    if (/[0-9]/.test(p)) s++;
    if (/[^A-Za-z0-9]/.test(p)) s++;
    return s;
  }, [form.password]);

  const strengthLabel = ['Too weak', 'Weak', 'Okay', 'Strong', 'Strong'][strength];
  const strengthColor = ['bg-gray-200', 'bg-rose-400', 'bg-amber-400', 'bg-emerald-500', 'bg-emerald-500'][
    strength
  ];

  const phone = form.phone.replace(/\D/g, '');

  const validateDetails = () => {
    if (!agree) return 'Please accept Terms to continue.';
    if (form.name.trim().length < 2) return 'Enter your full name.';
    if (phone.length !== 10 || !/^[6-9]/.test(phone)) return 'Enter a valid 10-digit mobile number.';
    if (form.password.length < 8) return 'Password must be at least 8 characters.';
    if (form.password !== form.confirm) return 'Passwords do not match.';
    return '';
  };

  const sendOtp = async () => {
    const err = validateDetails();
    if (err) {
      setError(err);
      return;
    }
    setLoading(true);
    setError('');
    setDevHint('');
    try {
      const res = await apiRequest('/auth/otp/send', {
        method: 'POST',
        body: JSON.stringify({ phone, purpose: 'VERIFY_PHONE' }),
      });
      setStep('otp');
      setCooldown(30);
      if (res.data?.devCode) setDevHint(`Dev OTP: ${res.data.devCode}`);
      setTimeout(() => otpRefs.current[0]?.focus(), 50);
    } catch (e: any) {
      setError(e.message || 'Could not send OTP');
    } finally {
      setLoading(false);
    }
  };

  const register = async (e: React.FormEvent) => {
    e.preventDefault();
    const code = otp.join('');
    if (code.length !== 6) {
      setError('Enter the 6-digit OTP sent to your phone.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const res = await apiRequest('/auth/register', {
        method: 'POST',
        body: JSON.stringify({
          name: form.name.trim(),
          phone,
          password: form.password,
          otp: code,
        }),
      });
      setCurrentUser(res.data.user);
      router.push('/');
    } catch (err: any) {
      setError(err.message || 'Registration failed');
    } finally {
      setLoading(false);
    }
  };

  const onOtpChange = (index: number, value: string) => {
    const digit = value.replace(/\D/g, '').slice(-1);
    const next = [...otp];
    next[index] = digit;
    setOtp(next);
    if (digit && index < 5) otpRefs.current[index + 1]?.focus();
  };

  const onOtpKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      otpRefs.current[index - 1]?.focus();
    }
  };

  const onOtpPaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
    if (!pasted) return;
    const next = Array(6).fill('');
    pasted.split('').forEach((d, i) => {
      next[i] = d;
    });
    setOtp(next);
    otpRefs.current[Math.min(pasted.length, 5)]?.focus();
  };

  return (
    <AuthShell
      title={step === 'details' ? 'Create account' : 'Verify mobile'}
      subtitle={
        step === 'details'
          ? 'Join MY11s in under a minute. We will verify your phone with an OTP.'
          : `Enter the 6-digit OTP sent to +91 ${phone}`
      }
    >
      {error && (
        <div className="mb-4">
          <AuthError message={error} />
          {error.toLowerCase().includes('already registered') && (
            <p className="mt-2 text-center text-xs">
              <Link href="/login" className="font-bold text-d11-red hover:underline">
                Go to login
              </Link>
            </p>
          )}
        </div>
      )}

      {step === 'details' ? (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            sendOtp();
          }}
          className="space-y-4"
        >
          <AuthField label="Full name">
            <div className="relative">
              <User className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                required
                autoComplete="name"
                minLength={2}
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                placeholder="As on your ID"
                className="d11-input pl-10"
              />
            </div>
          </AuthField>

          <AuthField label="Mobile number">
            <div className="flex overflow-hidden rounded-xl border border-gray-300 bg-white focus-within:border-d11-red focus-within:ring-2 focus-within:ring-d11-red/20">
              <span className="flex items-center gap-1.5 border-r border-gray-200 bg-gray-50 px-3 text-sm font-semibold text-gray-600">
                <Smartphone className="h-3.5 w-3.5 text-d11-muted" />
                +91
              </span>
              <input
                required
                inputMode="numeric"
                autoComplete="tel"
                maxLength={10}
                value={form.phone}
                onChange={(e) => setForm({ ...form, phone: e.target.value.replace(/\D/g, '').slice(0, 10) })}
                placeholder="10-digit number"
                className="min-w-0 flex-1 border-0 bg-transparent px-3.5 py-3 text-sm outline-none"
              />
            </div>
          </AuthField>

          <AuthField label="Password" hint="Min 8 characters">
            <div className="relative">
              <Lock className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                required
                type={showPw ? 'text' : 'password'}
                autoComplete="new-password"
                minLength={8}
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
                placeholder="Create a password"
                className="d11-input pl-10 pr-11"
              />
              <button
                type="button"
                onClick={() => setShowPw((v) => !v)}
                className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-gray-400 hover:text-gray-700"
                aria-label={showPw ? 'Hide password' : 'Show password'}
              >
                {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            {form.password.length > 0 && (
              <div className="mt-2">
                <div className="flex gap-1">
                  {[0, 1, 2, 3].map((i) => (
                    <span
                      key={i}
                      className={`h-1 flex-1 rounded-full ${i < strength ? strengthColor : 'bg-gray-200'}`}
                    />
                  ))}
                </div>
                <p className="mt-1 text-[11px] font-medium text-gray-500">{strengthLabel}</p>
              </div>
            )}
          </AuthField>

          <AuthField label="Confirm password">
            <input
              required
              type={showPw ? 'text' : 'password'}
              autoComplete="new-password"
              minLength={8}
              value={form.confirm}
              onChange={(e) => setForm({ ...form, confirm: e.target.value })}
              placeholder="Re-enter password"
              className="d11-input"
            />
          </AuthField>

          <button
            type="button"
            onClick={() => setAgree((v) => !v)}
            className="flex w-full cursor-pointer items-start gap-3 rounded-xl border border-gray-200 bg-gray-50 px-3.5 py-3 text-left"
          >
            <span
              className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border ${
                agree ? 'border-d11-red bg-d11-red text-white' : 'border-gray-300 bg-white'
              }`}
            >
              {agree && <Check className="h-3.5 w-3.5" strokeWidth={3} />}
            </span>
            <span className="text-xs leading-relaxed text-gray-600">
              I am 18+ and agree to the{' '}
              <Link href="/terms" className="font-bold text-d11-red hover:underline" onClick={(e) => e.stopPropagation()}>
                Terms
              </Link>{' '}
              and fantasy contest rules.
            </span>
          </button>

          <Button type="submit" loading={loading} className="w-full rounded-xl text-sm font-bold">
            Send OTP
          </Button>
        </form>
      ) : (
        <form onSubmit={register} className="space-y-4">
          <AuthField label="Enter OTP" hint="Valid for 5 minutes">
            <div className="flex justify-between gap-2" onPaste={onOtpPaste}>
              {otp.map((d, i) => (
                <input
                  key={i}
                  ref={(el) => {
                    otpRefs.current[i] = el;
                  }}
                  inputMode="numeric"
                  maxLength={1}
                  value={d}
                  onChange={(e) => onOtpChange(i, e.target.value)}
                  onKeyDown={(e) => onOtpKeyDown(i, e)}
                  className="h-12 w-11 rounded-xl border border-gray-300 text-center text-lg font-bold text-d11-ink outline-none transition focus:border-d11-red focus:ring-2 focus:ring-d11-red/20 sm:w-12"
                  aria-label={`Digit ${i + 1}`}
                />
              ))}
            </div>
          </AuthField>
          {devHint && process.env.NODE_ENV !== 'production' && (
            <p className="text-[11px] font-medium text-amber-600">{devHint}</p>
          )}

          <Button type="submit" loading={loading} className="w-full rounded-xl text-sm font-bold">
            Verify & create account
          </Button>

          <div className="flex flex-col gap-2 text-center text-xs">
            <button
              type="button"
              disabled={cooldown > 0 || loading}
              onClick={sendOtp}
              className="cursor-pointer font-bold text-d11-red disabled:cursor-not-allowed disabled:text-gray-400"
            >
              {cooldown > 0 ? `Resend OTP in ${cooldown}s` : 'Resend OTP'}
            </button>
            <button
              type="button"
              onClick={() => {
                setStep('details');
                setOtp(['', '', '', '', '', '']);
                setError('');
              }}
              className="cursor-pointer font-semibold text-gray-500 hover:text-d11-ink"
            >
              Change phone number
            </button>
          </div>
        </form>
      )}

      <p className="mt-6 text-center text-sm text-gray-500">
        Already have an account?{' '}
        <Link href="/login" className="font-bold text-d11-red hover:underline">
          Login
        </Link>
      </p>
    </AuthShell>
  );
}
