'use client';

import React, { useState, Suspense, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { 
  Phone, 
  KeyRound, 
  ArrowRight, 
  Sparkles, 
  ArrowLeft,
  CheckCircle2,
  AlertCircle,
  Shield
} from 'lucide-react';
import { toast } from 'sonner';
import { authApi } from '@/lib/api';
import { savePlatformSession } from '@/lib/auth';

const COUNTRIES = [
  { name: 'India', code: 'IN', dial_code: '91', flag: '🇮🇳', min_length: 10, max_length: 10 },
  { name: 'United States', code: 'US', dial_code: '1', flag: '🇺🇸', min_length: 10, max_length: 10 },
  { name: 'United Kingdom', code: 'GB', dial_code: '44', flag: '🇬🇧', min_length: 10, max_length: 10 },
  { name: 'United Arab Emirates', code: 'AE', dial_code: '971', flag: '🇦🇪', min_length: 9, max_length: 9 },
  { name: 'Canada', code: 'CA', dial_code: '1', flag: '🇨🇦', min_length: 10, max_length: 10 },
  { name: 'Australia', code: 'AU', dial_code: '61', flag: '🇦🇺', min_length: 9, max_length: 9 },
  { name: 'Saudi Arabia', code: 'SA', dial_code: '966', flag: '🇸🇦', min_length: 9, max_length: 9 },
  { name: 'Singapore', code: 'SG', dial_code: '65', flag: '🇸🇬', min_length: 8, max_length: 8 },
  { name: 'Germany', code: 'DE', dial_code: '49', flag: '🇩🇪', min_length: 10, max_length: 11 },
  { name: 'France', code: 'FR', dial_code: '33', flag: '🇫🇷', min_length: 9, max_length: 9 },
];

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectUrl = searchParams.get('redirect') || '/services';

  const [countryCode, setCountryCode] = useState('91');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [otp, setOtp] = useState(['', '', '', '']);
  const [step, setStep] = useState<'phone' | 'otp'>('phone');
  const [loading, setLoading] = useState(false);
  const [timer, setTimer] = useState(30);
  const [canResend, setCanResend] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const selectedCountry = COUNTRIES.find((c) => c.dial_code === countryCode) || COUNTRIES[0];

  useEffect(() => {
    let interval: any;
    if (step === 'otp' && timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => {
          if (prev <= 1) {
            setCanResend(true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [step, timer]);

  const handlePhoneChange = (val: string) => {
    const clean = val.replace(/\D/g, '').slice(0, selectedCountry.max_length);
    setPhoneNumber(clean);
  };

  const handleCountrySelect = (code: string) => {
    setCountryCode(code);
    setPhoneNumber('');
    setError(null);
  };

  const handleSendOtp = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setError(null);

    const cleanPhone = phoneNumber.trim().replace(/\D/g, '');
    if (cleanPhone.length < selectedCountry.min_length) {
      const msg = `Please enter a valid ${selectedCountry.name} mobile number (${selectedCountry.min_length} digits)`;
      setError(msg);
      toast.error(msg);
      return;
    }

    setLoading(true);
    try {
      await authApi.continueWithPhone({
        phone: cleanPhone,
        country_code: countryCode,
        type: 'customer',
      });
      setStep('otp');
      setTimer(30);
      setCanResend(false);
      toast.success('Verification code sent');
    } catch (err: any) {
      const errMsg = err?.response?.data?.message || err?.message || 'Failed to send OTP. Please try again.';
      setError(errMsg);
      toast.error(errMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleOtpChange = (index: number, value: string) => {
    const cleanVal = value.replace(/\D/g, '').slice(-1);
    const newOtp = [...otp];
    newOtp[index] = cleanVal;
    setOtp(newOtp);

    if (cleanVal && index < 3) {
      const nextInput = document.getElementById(`login-otp-slot-${index + 1}`);
      nextInput?.focus();
    }

    if (cleanVal && index === 3 && newOtp.every((d) => d.length === 1)) {
      handleVerifyOtp(newOtp.join(''));
    }
  };

  const handleOtpKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      const prevInput = document.getElementById(`login-otp-slot-${index - 1}`);
      prevInput?.focus();
    }
  };

  const handleVerifyOtp = async (fullOtp?: string | React.FormEvent) => {
    if (fullOtp && typeof fullOtp !== 'string' && 'preventDefault' in fullOtp) {
      fullOtp.preventDefault();
    }
    setError(null);

    const finalOtp = typeof fullOtp === 'string' ? fullOtp : otp.join('');
    if (finalOtp.length < 4) {
      setError('Please enter the 4-digit verification code');
      toast.error('Please enter the complete verification code');
      return;
    }

    setLoading(true);
    try {
      const response = await authApi.verifyPhone({
        otp: finalOtp,
        device_type: 'web',
        fcm_token: '',
      });

      const accessToken = response?.access_token || response?.token || response?.data?.access_token;
      const user = response?.data || response?.user;

      if (accessToken) {
        savePlatformSession(accessToken, user);
        toast.success('Successfully authenticated!');
        window.dispatchEvent(
          new CustomEvent('READY_MFE_EVENT', {
            detail: { type: 'MFE_AUTH_LOGIN', payload: { token: accessToken, user } },
          })
        );
        router.push(redirectUrl);
      } else {
        throw new Error('No access token returned from backend.');
      }
    } catch (err: any) {
      const errMsg = err?.response?.data?.message || err?.message || 'Invalid or expired OTP code.';
      setError(errMsg);
      toast.error(errMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative min-h-[85vh] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 bg-white bg-map-pattern">
      
      <div className="relative w-full max-w-md">
        <div className="rounded-3xl border border-neutral-200 bg-white p-8 shadow-xl text-neutral-900">
          
          {/* Header */}
          <div className="text-center mb-8">
            <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-black text-white shadow-md mb-4">
              <Sparkles className="h-7 w-7" />
            </div>
            <h1 className="text-2xl font-black tracking-tight text-black">
              {step === 'phone' ? 'Welcome Back' : 'Verify Your Number'}
            </h1>
            <p className="mt-2 text-xs text-neutral-500">
              {step === 'phone' 
                ? 'Sign in to access Food Delivery & Cab Booking with one account' 
                : `Enter the code sent to +${countryCode} ${phoneNumber}`}
            </p>
          </div>

          {error && (
            <div className="mb-6 flex items-start gap-2.5 rounded-xl border border-red-200 bg-red-50 p-3.5 text-xs text-red-700">
              <AlertCircle className="h-4 w-4 flex-shrink-0 text-red-600" />
              <span>{error}</span>
            </div>
          )}

          {/* Form */}
          {step === 'phone' ? (
            <form onSubmit={handleSendOtp} className="space-y-5">
              <div>
                <label className="block text-xs font-semibold uppercase tracking-wider text-neutral-600 mb-2">
                  Mobile Number
                </label>
                <div className="flex gap-2">
                  <select
                    value={countryCode}
                    onChange={(e) => handleCountrySelect(e.target.value)}
                    className="rounded-2xl border border-neutral-300 bg-neutral-50 px-3 py-3 text-sm text-black font-semibold focus:border-black focus:outline-none"
                  >
                    {COUNTRIES.map((c) => (
                      <option key={c.code} value={c.dial_code}>
                        {c.flag} +{c.dial_code} ({c.code})
                      </option>
                    ))}
                  </select>

                  <div className="relative flex-1">
                    <input
                      type="tel"
                      value={phoneNumber}
                      onChange={(e) => handlePhoneChange(e.target.value)}
                      maxLength={selectedCountry.max_length}
                      placeholder={`Enter ${selectedCountry.min_length} digit number`}
                      required
                      autoFocus
                      className="w-full rounded-2xl border border-neutral-300 bg-neutral-50 px-4 py-3 text-sm text-black placeholder-neutral-400 focus:border-black focus:outline-none"
                    />
                  </div>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading || phoneNumber.trim().length < selectedCountry.min_length}
                className="flex items-center justify-center gap-2 w-full rounded-full bg-black px-4 py-3.5 text-sm font-bold text-white shadow-md transition hover:bg-neutral-800 disabled:opacity-50"
              >
                {loading ? 'Sending OTP...' : 'Continue'}
                {!loading && <ArrowRight className="h-4 w-4" />}
              </button>

              <div className="flex items-center justify-center gap-2 text-xs text-neutral-500 pt-2">
                <Shield className="h-3.5 w-3.5 text-neutral-400" />
                <span>Your personal data is encrypted & secured</span>
              </div>
            </form>
          ) : (
            <div className="space-y-5">
              <div className="flex justify-center gap-3">
                {[0, 1, 2, 3].map((index) => (
                  <input
                    key={index}
                    id={`login-otp-slot-${index}`}
                    type="text"
                    maxLength={1}
                    value={otp[index]}
                    onChange={(e) => handleOtpChange(index, e.target.value)}
                    onKeyDown={(e) => handleOtpKeyDown(index, e)}
                    className="h-14 w-14 rounded-2xl border border-neutral-300 bg-neutral-100 text-center text-xl font-black text-black focus:border-black focus:bg-white focus:outline-none"
                  />
                ))}
              </div>

              <div className="flex items-center justify-between text-xs">
                <button
                  type="button"
                  onClick={() => {
                    setStep('phone');
                    setOtp(['', '', '', '']);
                    setError(null);
                  }}
                  className="flex items-center gap-1 text-neutral-600 hover:text-black transition"
                >
                  <ArrowLeft className="h-3.5 w-3.5" />
                  Change Phone Number
                </button>
                {canResend ? (
                  <button
                    type="button"
                    onClick={() => handleSendOtp()}
                    className="text-black font-semibold hover:underline transition"
                  >
                    Resend Code
                  </button>
                ) : (
                  <span className="text-neutral-500">
                    Resend in <span className="font-bold text-black">{timer}s</span>
                  </span>
                )}
              </div>

              {/* ReadyCab Demo Hint Box */}
              <div className="rounded-2xl bg-neutral-100 p-2.5 text-center text-xs font-semibold text-neutral-600">
                Your OTP is <span className="font-mono font-bold text-black">1234</span>
              </div>

              <button
                type="button"
                onClick={() => handleVerifyOtp()}
                disabled={loading || otp.join('').length < 4}
                className="flex items-center justify-center gap-2 w-full rounded-full bg-black px-4 py-3.5 text-sm font-bold text-white shadow-md transition hover:bg-neutral-800 disabled:opacity-50"
              >
                {loading ? 'Verifying...' : 'Verify & Sign In'}
                {!loading && <CheckCircle2 className="h-4 w-4" />}
              </button>
            </div>
          )}

          {/* Footer note */}
          <div className="mt-8 border-t border-neutral-200 pt-6 text-center text-xs text-neutral-500">
            <span>By proceeding, you agree to our </span>
            <Link href="/terms" className="text-black underline">Terms</Link>
            <span> and </span>
            <Link href="/privacy" className="text-black underline">Privacy Policy</Link>.
          </div>

        </div>

      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={
      <div className="min-h-[85vh] flex items-center justify-center bg-white">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-black"></div>
      </div>
    }>
      <LoginForm />
    </Suspense>
  );
}

