'use client';

import React, { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { countries } from '../../utils/countries';
import { getNationalMask, formatDigitsToMask } from '../../utils/phone-helpers';
import { firePixelEvent, setPixelUserData } from '../../tracking/firePixelEvent';
type Step = 'identifier' | 'returning' | 'new';

interface LoginFormProps {
  onSuccess?: () => void;
  onClose?: () => void;
}

const inputClass =
  'block w-full rounded-input border border-primary bg-primary px-3 py-2.5 text-sm text-primary placeholder-quaternary focus:border-brand focus:outline-none focus:ring-1 focus:ring-brand transition-colors';
const labelClass = 'block text-sm text-secondary mb-1';

function isValidEmail(value: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}

export function LoginForm({ onSuccess, onClose }: LoginFormProps) {
  const router = useRouter();
  const [step, setStep] = useState<Step>('identifier');

  // Identifier step state
  const [email, setEmail] = useState('');
  const [phoneValue, setPhoneValue] = useState(''); // formatted national number
  const [selectedCountry, setSelectedCountry] = useState('US');

  // Later steps
  const [welcomeName, setWelcomeName] = useState<string | null>(null);
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [password, setPassword] = useState('');
  const [passwordConfirm, setPasswordConfirm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // Phone helpers
  const country = useMemo(() => countries.find((c) => c.code === selectedCountry), [selectedCountry]);
  const phoneCode = country ? (country.phoneCode.startsWith('+') ? country.phoneCode : `+${country.phoneCode}`) : '+1';
  const nationalMask = useMemo(() => getNationalMask(country), [country]);
  const nationalPlaceholder = nationalMask ? nationalMask.replace(/#/g, '0') : '(555) 000-0000';
  const countryOptions = useMemo(
    () => countries.map((c) => ({ label: c.phoneCode.startsWith('+') ? c.phoneCode : `+${c.phoneCode}`, value: c.code })),
    []
  );

  // Computed API values
  const phoneDigits = phoneValue.replace(/\D/g, '');
  const fullPhone = phoneDigits.length > 0 ? `${phoneCode}${phoneDigits}` : null;
  const emailVal = email.trim() || null;

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const digits = e.target.value.replace(/\D/g, '');
    const formatted = nationalMask ? formatDigitsToMask(digits, nationalMask) : digits;
    setPhoneValue(formatted);
  };

  const handleContinue = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!emailVal && !fullPhone) { setError('Enter your email address or phone number to continue.'); return; }
    if (emailVal && !isValidEmail(emailVal)) { setError('Enter a valid email address.'); return; }
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/consumer/initiate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: emailVal, phone: fullPhone }),
      });
      const result = await res.json().catch(() => ({ exists: null }));
      if (result.exists === true) {
        await setPixelUserData({ email: emailVal, phone: fullPhone });
        firePixelEvent('Lead');
        setWelcomeName(result.firstName ?? null);
        setStep(result.hasPassword === false ? 'new' : 'returning');
      } else if (result.exists === false) {
        await setPixelUserData({ email: emailVal, phone: fullPhone });
        firePixelEvent('Lead');
        setStep('new');
      } else {
        setError('Something went wrong. Please check your connection and try again.');
      }
    } catch {
      setError('Something went wrong. Please check your connection and try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleSignIn = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/consumer/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: emailVal, phone: fullPhone, password }),
      });
      const result = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (result.code === 'not_found' || result.code === 'no_password') {
          setStep('new');
          setError(null);
          return;
        }
        setError(result.error || 'Login failed. Please try again.');
        return;
      }
      if (onSuccess) onSuccess(); else router.refresh();
    } catch {
      setError('Something went wrong. Please check your connection and try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleSignUp = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== passwordConfirm) { setError('Passwords do not match.'); return; }
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/consumer/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: emailVal,
          phone: fullPhone,
          password,
          password_confirmation: passwordConfirm,
          first_name: firstName.trim() || undefined,
          last_name: lastName.trim() || undefined,
        }),
      });
      const result = await res.json().catch(() => ({}));
      if (!res.ok) { setError(result.error || 'Signup failed. Please try again.'); return; }
      if (onSuccess) onSuccess(); else router.refresh();
    } catch {
      setError('Something went wrong. Please check your connection and try again.');
    } finally {
      setLoading(false);
    }
  };

  const goBack = () => {
    setStep('identifier');
    setPassword('');
    setPasswordConfirm('');
    setError(null);
  };

  const identifierSummary = [emailVal, fullPhone].filter(Boolean).join(' / ');

  const headerTitle =
    step === 'identifier' ? 'Pricing & Booking Portal' :
    step === 'returning' ? (welcomeName ? `Welcome back, ${welcomeName}!` : 'Welcome back!') :
    (welcomeName ? `Welcome back, ${welcomeName}!` : 'Welcome!');

  const headerSubtitle =
    step === 'identifier' ? 'Enter your email or phone number to get started.' :
    step === 'returning' ? 'Enter your password to sign in.' :
    (welcomeName ? 'Create a password to access your account.' : "Let's get you set up.");

  return (
    <div>
      {/* Header */}
      <div className="flex items-start justify-between gap-4 mb-5">
        <div>
          <h3 className="text-lg font-normal text-primary">{headerTitle}</h3>
          <p className="mt-0.5 text-sm text-tertiary">{headerSubtitle}</p>
        </div>
        {onClose && (
          <button
            type="button"
            onClick={onClose}
            className="shrink-0 p-1 text-tertiary hover:text-primary transition-colors"
            aria-label="Close"
          >
            <svg className="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        )}
      </div>

      {error && (
        <div className="mb-4 rounded-input border border-error bg-error-primary px-3 py-2 text-sm text-error-primary">
          {error}
        </div>
      )}

      {/* Step: identifier */}
      {step === 'identifier' && (
        <form onSubmit={handleContinue} className="space-y-3">
          <div>
            <label className={labelClass}>Email address</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
              className={inputClass}
              autoComplete="email"
              autoFocus
            />
          </div>
          <div className="flex items-center gap-3">
            <hr className="flex-1 border-secondary" />
            <span className="text-xs text-quaternary">or</span>
            <hr className="flex-1 border-secondary" />
          </div>
          <div>
            <label className={labelClass}>Phone number</label>
            <div className="flex rounded-input border border-primary overflow-hidden focus-within:border-brand focus-within:ring-1 focus-within:ring-brand transition-colors">
              <select
                value={selectedCountry}
                onChange={(e) => { setSelectedCountry(e.target.value); setPhoneValue(''); }}
                className="border-r border-secondary bg-secondary px-2 py-2.5 text-sm text-secondary focus:outline-none"
                aria-label="Country code"
              >
                {countryOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
              <input
                type="tel"
                value={phoneValue}
                onChange={handlePhoneChange}
                placeholder={nationalPlaceholder}
                className="flex-1 px-3 py-2.5 text-sm text-primary placeholder-quaternary bg-transparent focus:outline-none"
              />
            </div>
          </div>
          <div className="pt-1">
            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-interactive bg-brand-solid px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-solid_hover transition-colors disabled:opacity-50"
            >
              {loading ? 'Looking you up…' : 'Continue'}
            </button>
          </div>
        </form>
      )}

      {/* Step: returning user */}
      {step === 'returning' && (
        <form onSubmit={handleSignIn} className="space-y-3">
          <div>
            <label className={labelClass}>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              className={inputClass}
              required
              autoComplete="current-password"
              autoFocus
            />
          </div>
          <div className="pt-1">
            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-interactive bg-brand-solid px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-solid_hover transition-colors disabled:opacity-50"
            >
              {loading ? 'Signing in…' : 'Sign in'}
            </button>
          </div>
          <button
            type="button"
            onClick={goBack}
            className="w-full text-center text-sm text-tertiary hover:text-primary transition-colors"
          >
            ← {identifierSummary ? `Not ${identifierSummary}?` : 'Change email or phone'}
          </button>
        </form>
      )}

      {/* Step: new user / claim account */}
      {step === 'new' && (
        <form onSubmit={handleSignUp} className="space-y-3">
          {/* Only ask for name if we don't already know who they are */}
          {!welcomeName && (
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelClass}>First name</label>
                <input
                  type="text"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  placeholder="Jane"
                  className={inputClass}
                  autoComplete="given-name"
                  autoFocus
                />
              </div>
              <div>
                <label className={labelClass}>Last name</label>
                <input
                  type="text"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  placeholder="Smith"
                  className={inputClass}
                  autoComplete="family-name"
                />
              </div>
            </div>
          )}
          <div>
            <label className={labelClass}>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              className={inputClass}
              required
              autoComplete="new-password"
              autoFocus={!!welcomeName}
            />
          </div>
          <div>
            <label className={labelClass}>Confirm password</label>
            <input
              type="password"
              value={passwordConfirm}
              onChange={(e) => setPasswordConfirm(e.target.value)}
              placeholder="••••••••"
              className={inputClass}
              required
              autoComplete="new-password"
            />
          </div>
          <div className="pt-1">
            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-interactive bg-brand-solid px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-solid_hover transition-colors disabled:opacity-50"
            >
              {loading ? 'Creating account…' : 'Create account'}
            </button>
          </div>
          <button
            type="button"
            onClick={goBack}
            className="w-full text-center text-sm text-tertiary hover:text-primary transition-colors"
          >
            ← Back
          </button>
        </form>
      )}
    </div>
  );
}
