'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

const API_BASE = process.env['NEXT_PUBLIC_API_URL'] ?? 'http://localhost:3001';

type Step = 'phone' | 'code';

export default function MemberLoginPage() {
  const router = useRouter();
  const [step, setStep] = useState<Step>('phone');
  const [phone, setPhone] = useState('');
  const [challengeId, setChallengeId] = useState('');
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function requestOtp() {
    setError(null);
    setBusy(true);
    try {
      const res = await fetch(`${API_BASE}/public/auth/member-login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone }),
      });
      const data = (await res.json().catch(() => ({}))) as { challengeId?: string; message?: string };
      if (!res.ok) {
        setError(data.message ?? 'Failed to send code');
        return;
      }
      setChallengeId(data.challengeId ?? '');
      setStep('code');
    } finally {
      setBusy(false);
    }
  }

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

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="w-full max-w-sm bg-white rounded-2xl border border-gray-200 shadow-sm p-7 space-y-6">
        <div>
          <div className="w-10 h-10 rounded-xl bg-indigo-100 flex items-center justify-center text-xl mb-4">🏠</div>
          <h1 className="text-lg font-semibold text-gray-900">Sign in to your portal</h1>
          <p className="text-sm text-gray-500 mt-1">
            {step === 'phone'
              ? 'Enter your WhatsApp number and we\'ll send you a code.'
              : `We sent a 6-digit code to ${phone} on WhatsApp.`}
          </p>
        </div>

        {step === 'phone' && (
          <div className="space-y-4">
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+91 98765 43210"
              autoFocus
              className="w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
            {error && <p className="text-sm text-red-600">{error}</p>}
            <button
              type="button"
              onClick={requestOtp}
              disabled={busy || phone.replace(/\D/g, '').length < 8}
              className="w-full rounded-lg bg-indigo-600 text-white text-sm font-medium py-2.5 hover:bg-indigo-700 disabled:opacity-50 transition-colors"
            >
              {busy ? 'Sending…' : 'Send code'}
            </button>
            <p className="text-xs text-center text-gray-400">
              First time?{' '}
              <a href="/onboard" className="text-indigo-600 hover:underline">
                Use your invite link
              </a>
            </p>
          </div>
        )}

        {step === 'code' && (
          <div className="space-y-4">
            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]{6}"
              maxLength={6}
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
              placeholder="000000"
              autoFocus
              className="w-full rounded-lg border border-gray-300 px-3 py-2.5 text-center text-lg tracking-[0.3em] font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
            <button
              type="button"
              onClick={requestOtp}
              disabled={busy}
              className="text-xs text-indigo-600 hover:underline disabled:opacity-50 w-full text-center"
            >
              Didn't get it? Resend code
            </button>
            {error && <p className="text-sm text-red-600">{error}</p>}
            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => { setStep('phone'); setCode(''); setError(null); }}
                className="rounded-lg border border-gray-300 text-gray-600 text-sm font-medium px-4 py-2.5 hover:bg-gray-50"
              >
                Back
              </button>
              <button
                type="button"
                onClick={verifyOtp}
                disabled={busy || code.length < 6}
                className="flex-1 rounded-lg bg-indigo-600 text-white text-sm font-medium py-2.5 hover:bg-indigo-700 disabled:opacity-50 transition-colors"
              >
                {busy ? 'Verifying…' : 'Sign in'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
