import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Loader2, Phone, MessageCircle } from 'lucide-react';

type Channel = 'whatsapp' | 'sms';
type Step = 'phone' | 'otp';

// Common country codes for Latin America
const countryCodes = [
  { code: '52', country: 'Mexico', flag: 'MX' },
  { code: '1', country: 'USA', flag: 'US' },
  { code: '57', country: 'Colombia', flag: 'CO' },
  { code: '54', country: 'Argentina', flag: 'AR' },
  { code: '56', country: 'Chile', flag: 'CL' },
  { code: '51', country: 'Peru', flag: 'PE' },
  { code: '593', country: 'Ecuador', flag: 'EC' },
  { code: '58', country: 'Venezuela', flag: 'VE' },
  { code: '34', country: 'Espana', flag: 'ES' },
];

export function PhoneLoginForm() {
  const navigate = useNavigate();
  const [step, setStep] = useState<Step>('phone');
  const [channel, setChannel] = useState<Channel>('whatsapp');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    countryCode: '52',
    phoneNumber: '',
    otpCode: '',
  });

  const [otpExpiresAt, setOtpExpiresAt] = useState<Date | null>(null);

  const handleSendOTP = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/auth/phone/send-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          phoneNumber: formData.phoneNumber,
          countryCode: formData.countryCode,
          channel,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Error al enviar el codigo');
      }

      setOtpExpiresAt(new Date(data.data.expiresAt));
      setStep('otp');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error desconocido');
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerifyOTP = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/auth/phone/verify-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          phoneNumber: formData.phoneNumber,
          countryCode: formData.countryCode,
          otpCode: formData.otpCode,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Codigo invalido');
      }

      // Store tokens
      localStorage.setItem('accessToken', data.data.tokens.accessToken);
      localStorage.setItem('refreshToken', data.data.tokens.refreshToken);

      // Redirect
      navigate('/dashboard');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error desconocido');
    } finally {
      setIsLoading(false);
    }
  };

  const handleResendOTP = async () => {
    setFormData({ ...formData, otpCode: '' });
    setError(null);
    await handleSendOTP({ preventDefault: () => {} } as React.FormEvent);
  };

  if (step === 'otp') {
    return (
      <form onSubmit={handleVerifyOTP} className="space-y-4">
        {error && (
          <div className="p-3 rounded-lg bg-red-900/30 border border-red-800 text-red-400 text-sm">
            {error}
          </div>
        )}

        <div className="text-center mb-4">
          <p className="text-gray-400 text-sm">
            Enviamos un codigo de 6 digitos a
          </p>
          <p className="text-white font-medium">
            +{formData.countryCode} {formData.phoneNumber}
          </p>
        </div>

        <div>
          <label className="label">Codigo de verificacion</label>
          <input
            type="text"
            className="input text-center text-2xl tracking-[0.5em]"
            placeholder="000000"
            maxLength={6}
            value={formData.otpCode}
            onChange={(e) => setFormData({ ...formData, otpCode: e.target.value.replace(/\D/g, '') })}
            autoFocus
            required
          />
        </div>

        <button
          type="submit"
          disabled={isLoading || formData.otpCode.length !== 6}
          className="btn btn-primary w-full flex items-center justify-center gap-2"
        >
          {isLoading ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Verificando...
            </>
          ) : (
            'Verificar Codigo'
          )}
        </button>

        <div className="flex items-center justify-between text-sm">
          <button
            type="button"
            onClick={() => {
              setStep('phone');
              setFormData({ ...formData, otpCode: '' });
              setError(null);
            }}
            className="text-gray-400 hover:text-white"
          >
            Cambiar numero
          </button>
          <button
            type="button"
            onClick={handleResendOTP}
            disabled={isLoading}
            className="text-primary-400 hover:text-primary-300"
          >
            Reenviar codigo
          </button>
        </div>
      </form>
    );
  }

  return (
    <form onSubmit={handleSendOTP} className="space-y-4">
      {error && (
        <div className="p-3 rounded-lg bg-red-900/30 border border-red-800 text-red-400 text-sm">
          {error}
        </div>
      )}

      {/* Channel Selection */}
      <div className="flex gap-2">
        <button
          type="button"
          onClick={() => setChannel('whatsapp')}
          className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-colors ${
            channel === 'whatsapp'
              ? 'bg-green-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          <MessageCircle className="w-4 h-4" />
          WhatsApp
        </button>
        <button
          type="button"
          onClick={() => setChannel('sms')}
          className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-colors ${
            channel === 'sms'
              ? 'bg-blue-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          <Phone className="w-4 h-4" />
          SMS
        </button>
      </div>

      {/* Phone Number Input */}
      <div>
        <label className="label">Numero de telefono</label>
        <div className="flex gap-2">
          <select
            className="input w-28"
            value={formData.countryCode}
            onChange={(e) => setFormData({ ...formData, countryCode: e.target.value })}
          >
            {countryCodes.map((c) => (
              <option key={c.code} value={c.code}>
                +{c.code}
              </option>
            ))}
          </select>
          <input
            type="tel"
            className="input flex-1"
            placeholder="55 1234 5678"
            value={formData.phoneNumber}
            onChange={(e) => setFormData({ ...formData, phoneNumber: e.target.value.replace(/\D/g, '') })}
            required
          />
        </div>
      </div>

      <button
        type="submit"
        disabled={isLoading || formData.phoneNumber.length < 8}
        className="btn btn-primary w-full flex items-center justify-center gap-2"
      >
        {isLoading ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin" />
            Enviando...
          </>
        ) : (
          <>
            Enviar Codigo via {channel === 'whatsapp' ? 'WhatsApp' : 'SMS'}
          </>
        )}
      </button>

      <p className="text-xs text-gray-500 text-center">
        Al continuar, aceptas recibir mensajes de verificacion de OrbiQuant
      </p>
    </form>
  );
}
