'use client';

import { useState } from 'react';
import { CheckCircle2, Loader2, Smartphone } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PhilippinePhoneInput } from '@/components/ui/PhilippinePhoneInput';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import {
  formatPhilippinePhoneDisplay,
  isValidPhilippineLocalPhone,
  normalizePhilippinePhone,
} from '@/lib/phone';
import { cn } from '@/lib/utils';

type Props = {
  className?: string;
  /** Optional bilingual helper — defaults to English */
  t?: (en: string, tl: string) => string;
};

export function PhoneVerificationCard({ className, t = (en) => en }: Props) {
  const { user, refreshUser } = useAuth();
  const [phoneLocal, setPhoneLocal] = useState('');
  const [otp, setOtp] = useState('');
  const [otpSent, setOtpSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const phoneVerified = user?.phoneVerified === true;
  const savedPhone = user?.phone;

  async function sendCode(e?: React.FormEvent) {
    e?.preventDefault();
    setError('');
    setSuccess('');
    if (!isValidPhilippineLocalPhone(phoneLocal)) {
      setError(t('Enter a valid Philippine mobile number', 'Maglagay ng valid na Philippine mobile number'));
      return;
    }
    setLoading(true);
    try {
      await api('/auth/phone/send-otp', {
        method: 'POST',
        body: JSON.stringify({ phone: normalizePhilippinePhone(phoneLocal) }),
      });
      setOtpSent(true);
      setSuccess(
        t(
          `Code sent to ${formatPhilippinePhoneDisplay(phoneLocal)}. Check your SMS (dev: see API console).`,
          `Naipadala ang code sa ${formatPhilippinePhoneDisplay(phoneLocal)}.`
        )
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : t('Failed to send code', 'Hindi naipadala ang code'));
    } finally {
      setLoading(false);
    }
  }

  async function verifyCode(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSuccess('');
    if (otp.length < 6) {
      setError(t('Enter the 6-digit code', 'Ilagay ang 6-digit code'));
      return;
    }
    setLoading(true);
    try {
      await api('/auth/phone/verify', {
        method: 'POST',
        body: JSON.stringify({
          phone: normalizePhilippinePhone(phoneLocal),
          otpCode: otp,
        }),
      });
      setSuccess(t('Phone number verified', 'Na-verify na ang cellphone number'));
      setOtpSent(false);
      setOtp('');
      await refreshUser();
    } catch (err) {
      setError(err instanceof Error ? err.message : t('Verification failed', 'Hindi na-verify'));
    } finally {
      setLoading(false);
    }
  }

  return (
    <Card className={cn(className)}>
      <CardContent className="space-y-4 p-5">
        <div className="flex items-start gap-3">
          {phoneVerified ? (
            <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-emerald-600" />
          ) : (
            <Smartphone className="mt-0.5 h-5 w-5 shrink-0 text-amber-600" />
          )}
          <div className="min-w-0 flex-1">
            <h3 className="font-semibold text-slate-900">
              {t('Mobile number', 'Numero ng cellphone')}
              <span className="text-red-500"> *</span>
            </h3>
            <p className="mt-0.5 text-sm text-muted">
              {phoneVerified
                ? t(
                    `Verified: ${savedPhone ? formatPhilippinePhoneDisplay(savedPhone) : ''}`,
                    `Verified: ${savedPhone ? formatPhilippinePhoneDisplay(savedPhone) : ''}`
                  )
                : t(
                    'Required for account verification. We’ll send a one-time code to your phone.',
                    'Kailangan para sa verification. Magpapadala kami ng one-time code sa cellphone mo.'
                  )}
            </p>
          </div>
        </div>

        {!phoneVerified && (
          <form onSubmit={otpSent ? verifyCode : sendCode} className="space-y-3">
            <PhilippinePhoneInput
              label={t('Phone number', 'Numero ng cellphone')}
              value={phoneLocal}
              onChange={(v) => {
                setPhoneLocal(v);
                if (otpSent) {
                  setOtpSent(false);
                  setOtp('');
                }
              }}
              required
            />
            {otpSent && (
              <Input
                label={t('Verification code', 'Verification code')}
                value={otp}
                onChange={(e) => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                inputMode="numeric"
                maxLength={6}
                placeholder="000000"
                required
              />
            )}
            {error && <p className="text-sm text-red-600">{error}</p>}
            {success && <p className="text-sm text-emerald-700">{success}</p>}
            <div className="flex flex-wrap gap-2">
              {!otpSent ? (
                <Button
                  type="submit"
                  size="sm"
                  disabled={loading || !isValidPhilippineLocalPhone(phoneLocal)}
                >
                  {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {t('Send code', 'Ipadala ang code')}
                </Button>
              ) : (
                <>
                  <Button type="submit" size="sm" disabled={loading || otp.length < 6}>
                    {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                    {t('Verify phone', 'I-verify ang phone')}
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    disabled={loading}
                    onClick={() => sendCode()}
                  >
                    {t('Resend code', 'I-resend ang code')}
                  </Button>
                </>
              )}
            </div>
          </form>
        )}
      </CardContent>
    </Card>
  );
}
