/**
 * Unified Signup Form with Integrated Pricing Selection
 * Combines free and paid signup flows in one modern interface
 * 
 * Payment Flow (Simplified):
 * 1. User selects plan and fills in details
 * 2. User selects country from dropdown
 * 3. On submit: account created, redirected to /account/plans for payment
 * 
 * NO payment method selection at signup - this happens on /account/plans
 */

import { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Link, useNavigate } from 'react-router-dom';
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon, CheckIcon, Loader2Icon, CheckCircleIcon, GlobeIcon } from '../../icons';
import Label from '../form/Label';
import Input from '../form/input/InputField';
import Checkbox from '../form/input/Checkbox';
import Button from '../ui/button/Button';
import { useAuthStore } from '../../store/authStore';
import { fetchCountries } from '../../utils/countries';

interface Plan {
  id: number;
  name: string;
  slug: string;
  price: string | number;
  billing_cycle: string;
  is_active: boolean;
  max_users: number;
  max_sites: number;
  max_keywords: number;
  max_ahrefs_queries: number;
  included_credits: number;
  features: string[];
  annual_discount_percent?: number;
}

interface Country {
  code: string;
  name: string;
}

interface SignUpFormUnifiedProps {
  plans: Plan[];
  selectedPlan: Plan | null;
  onPlanSelect: (plan: Plan) => void;
  plansLoading: boolean;
}

export default function SignUpFormUnified({
  plans,
  selectedPlan,
  onPlanSelect,
  plansLoading,
}: SignUpFormUnifiedProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [isChecked, setIsChecked] = useState(false);
  const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annually'>('monthly');
  const [annualDiscountPercent, setAnnualDiscountPercent] = useState(15);

  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    accountName: '',
    billingCountry: 'US',
  });

  // Countries for dropdown
  const [countries, setCountries] = useState<Country[]>([]);
  const [countriesLoading, setCountriesLoading] = useState(true);
  const [error, setError] = useState('');

  const navigate = useNavigate();
  const { register, loading } = useAuthStore();

  const isPaidPlan = selectedPlan && parseFloat(String(selectedPlan.price || 0)) > 0;

  // Update URL when plan changes
  useEffect(() => {
    if (selectedPlan) {
      const url = new URL(window.location.href);
      url.searchParams.set('plan', selectedPlan.slug);
      window.history.replaceState({}, '', url.toString());
    }
  }, [selectedPlan]);

  // Load annual discount percent from plans
  useEffect(() => {
    if (plans.length > 0) {
      const planWithDiscount = plans.find(p => p.annual_discount_percent && p.annual_discount_percent > 0);
      if (planWithDiscount && planWithDiscount.annual_discount_percent) {
        setAnnualDiscountPercent(planWithDiscount.annual_discount_percent);
      }
    }
  }, [plans]);

  // Load countries from backend and detect user's country
  useEffect(() => {
    const loadCountriesAndDetect = async () => {
      setCountriesLoading(true);
      try {
        const loadedCountries = await fetchCountries();
        setCountries(loadedCountries);

        // Try to detect user's country for default selection
        // Note: This may fail due to CORS - that's expected and handled gracefully
        try {
          const geoResponse = await fetch('https://ipapi.co/country_code/', {
            signal: AbortSignal.timeout(3000),
            mode: 'cors',
          });
          if (geoResponse.ok) {
            const countryCode = await geoResponse.text();
            if (countryCode && countryCode.length === 2) {
              setFormData(prev => ({ ...prev, billingCountry: countryCode.trim() }));
            }
          }
        } catch (error) {
          // Silently fail - CORS or network error, keep default US
          // This is expected behavior and not a critical error
        }
      } finally {
        setCountriesLoading(false);
      }
    };

    loadCountriesAndDetect();
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!formData.email || !formData.password || !formData.firstName || !formData.lastName) {
      setError('Please fill in all required fields');
      return;
    }

    if (!isChecked) {
      setError('Please agree to the Terms and Conditions');
      return;
    }

    if (!selectedPlan) {
      setError('Please select a plan');
      return;
    }

    try {
      const username = formData.email.split('@')[0];

      const registerPayload: any = {
        email: formData.email,
        password: formData.password,
        username: username,
        first_name: formData.firstName,
        last_name: formData.lastName,
        account_name: formData.accountName,
        plan_slug: selectedPlan.slug,
        billing_country: formData.billingCountry,
      };

      const user = (await register(registerPayload)) as any;

      console.log('Registration response:', {
        user: user,
        accountStatus: user?.account?.status,
        planSlug: selectedPlan.slug,
      });

      // Verify auth state is actually set in Zustand store
      const currentAuthState = useAuthStore.getState();
      
      // If for some reason state wasn't set, force set it again
      if (!currentAuthState.isAuthenticated || !currentAuthState.user || !currentAuthState.token) {
        console.error('Auth state not properly set after registration, forcing update...');
        
        const tokenData = user?.tokens || {};
        const accessToken = user?.access || tokenData.access || localStorage.getItem('access_token');
        const refreshToken = user?.refresh || tokenData.refresh || localStorage.getItem('refresh_token');
        
        useAuthStore.setState({
          user: user,
          token: accessToken,
          refreshToken: refreshToken,
          isAuthenticated: true,
          loading: false
        });
        
        await new Promise((resolve) => setTimeout(resolve, 500));
      }

      // Final verification before navigation
      const finalState = useAuthStore.getState();
      if (!finalState.isAuthenticated) {
        throw new Error('Failed to authenticate after registration. Please try logging in manually.');
      }

      // Simplified navigation:
      // - Paid plans: Go to /account/plans to select payment method and complete payment
      // - Free plans: Go to sites page
      if (isPaidPlan) {
        console.log('Paid plan selected, redirecting to /account/plans for payment');
        navigate('/account/plans', { replace: true });
      } else {
        console.log('Free plan selected, redirecting to /sites');
        navigate('/sites', { replace: true });
      }
    } catch (err: any) {
      setError(err.message || 'Registration failed. Please try again.');
    }
  };

  const formatNumber = (num: number): string => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
    if (num >= 1000) return `${(num / 1000).toFixed(0)}K`;
    return num.toString();
  };

  const extractFeatures = (plan: Plan): string[] => {
    // Use features from plan's JSON field if available, otherwise build from limits
    if (plan.features && plan.features.length > 0) {
      return plan.features;
    }
    
    // Fallback to building from plan limits
    const features: string[] = [];
    features.push(`${plan.max_sites} ${plan.max_sites === 1 ? 'Site' : 'Sites'}`);
    features.push(`${plan.max_users} ${plan.max_users === 1 ? 'User' : 'Users'}`);
    features.push(`${formatNumber(plan.max_keywords || 0)} Keywords`);
    features.push(`${formatNumber(plan.included_credits || 0)} Credits/Month`);
    return features;
  };

  const getDisplayPrice = (plan: Plan): number => {
    const monthlyPrice = typeof plan.price === 'number' ? plan.price : parseFloat(String(plan.price || 0));
    if (billingPeriod === 'annually') {
      const discountMultiplier = 1 - (annualDiscountPercent / 100);
      return monthlyPrice * 12 * discountMultiplier;
    }
    return monthlyPrice;
  };

  return (
    <div className="flex flex-col lg:w-1/2 w-full">
      {/* Mobile Pricing Toggle */}
      <div className="lg:hidden bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 p-4">
        <div className="flex items-center justify-center gap-3">
          <div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-lg shadow-sm">
            <span
              className={`absolute top-1/2 left-1 flex h-9 w-28 -translate-y-1/2 rounded-md bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
                billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-28'
              }`}
            ></span>
            <button
              type="button"
              onClick={() => setBillingPeriod('monthly')}
              className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
                billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white'
              }`}
            >
              Monthly
            </button>
            <button
              type="button"
              onClick={() => setBillingPeriod('annually')}
              className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
                billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white'
              }`}
            >
              Annually
            </button>
          </div>
          <span className={`inline-flex items-center gap-1.5 text-xs text-success-600 dark:text-success-400 font-semibold bg-success-50 dark:bg-success-900/20 px-2 py-1 rounded-full transition-opacity duration-200 ${
            billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
          }`}>
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            Save up to {annualDiscountPercent}%
          </span>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto no-scrollbar flex items-center">
        <div className="w-full mx-auto p-6 sm:p-8 max-w-[572px]">
          <div className="mb-6">
            <h1 className="mb-2 font-semibold text-gray-800 dark:text-white text-2xl">Sign Up for {selectedPlan?.name || 'IGNY8'}</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Complete your registration and select a payment method.
            </p>
          </div>

          {/* Plan Selection - Mobile */}
          <div className="lg:hidden mb-6">
            <Label>Select Plan</Label>
            <div className="grid grid-cols-2 gap-2 mt-2">
              {plans.map((plan) => {
                const displayPrice = getDisplayPrice(plan);
                const isSelected = selectedPlan?.id === plan.id;
                const isFree = parseFloat(String(plan.price || 0)) === 0;

                return (
                  <Button
                    key={plan.id}
                    variant="ghost"
                    tone="neutral"
                    size="md"
                    onClick={() => onPlanSelect(plan)}
                    className={`p-3 rounded-lg border-2 text-left transition-all ${
                      isSelected
                        ? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
                        : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                    }`}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className={`font-semibold text-sm ${isSelected ? 'text-brand-600 dark:text-brand-400' : 'text-gray-900 dark:text-white'}`}>
                        {plan.name}
                      </span>
                      {isSelected && <CheckCircleIcon className="w-4 h-4 text-brand-500" />}
                    </div>
                    <div className="text-lg font-bold text-gray-900 dark:text-white">
                      {isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      {billingPeriod === 'annually' && !isFree ? '/year' : '/month'}
                    </div>
                  </Button>
                );
              })}
            </div>
          </div>

          {error && (
            <div className="mb-4 p-3 text-sm text-error-600 bg-error-50 border border-error-200 rounded-lg dark:bg-error-900/20 dark:text-error-400 dark:border-error-800">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div>
                <Label>
                  First Name<span className="text-error-500">*</span>
                </Label>
                <Input type="text" name="firstName" value={formData.firstName} onChange={handleChange} placeholder="Enter your first name" />
              </div>
              <div>
                <Label>
                  Last Name<span className="text-error-500">*</span>
                </Label>
                <Input type="text" name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Enter your last name" />
              </div>
            </div>

            <div>
              <Label>
                Email<span className="text-error-500">*</span>
              </Label>
              <Input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Enter your email" />
            </div>

            <div>
              <Label>Account Name (optional)</Label>
              <Input type="text" name="accountName" value={formData.accountName} onChange={handleChange} placeholder="Workspace / Company name" />
            </div>

            <div>
              <Label>
                Password<span className="text-error-500">*</span>
              </Label>
              <div className="relative">
                <Input placeholder="Enter your password" type={showPassword ? 'text' : 'password'} name="password" value={formData.password} onChange={handleChange} />
                <span onClick={() => setShowPassword(!showPassword)} className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2">
                  {showPassword ? <EyeIcon className="fill-gray-500 dark:fill-gray-400 size-5" /> : <EyeCloseIcon className="fill-gray-500 dark:fill-gray-400 size-5" />}
                </span>
              </div>
            </div>

            {/* Country Selection */}
            <div>
              <Label className="flex items-center gap-1.5">
                <GlobeIcon className="w-4 h-4 text-gray-500" />
                Country<span className="text-error-500">*</span>
              </Label>
              {countriesLoading ? (
                <div className="flex items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                  <Loader2Icon className="w-4 h-4 animate-spin text-brand-500 mr-2" />
                  <span className="text-sm text-gray-500">Loading countries...</span>
                </div>
              ) : (
                <select
                  name="billingCountry"
                  value={formData.billingCountry}
                  onChange={handleChange}
                  className="w-full px-4 py-3 text-sm text-gray-900 bg-white border border-gray-200 rounded-lg dark:bg-gray-800 dark:text-white dark:border-gray-700 focus:ring-2 focus:ring-brand-500 focus:border-transparent appearance-none cursor-pointer"
                >
                  {countries.map((country) => (
                    <option key={country.code} value={country.code}>
                      {country.name}
                    </option>
                  ))}
                </select>
              )}
            </div>

            <div className="flex items-start gap-3 pt-2">
              <Checkbox className="w-5 h-5 mt-0.5" checked={isChecked} onChange={setIsChecked} />
              <p className="text-sm text-gray-500 dark:text-gray-400">
                By creating an account means you agree to the{' '}
                <Link to="/terms" className="text-brand-500 hover:text-brand-600 dark:text-brand-400 hover:underline">
                  Terms and Conditions
                </Link>
                , and our{' '}
                <Link to="/privacy" className="text-brand-500 hover:text-brand-600 dark:text-brand-400 hover:underline">
                  Privacy Policy
                </Link>
              </p>
            </div>

            <Button type="submit" variant="primary" disabled={loading} className="w-full">
              {loading ? (
                <span className="flex items-center justify-center">
                  <Loader2Icon className="w-4 h-4 animate-spin mr-2" />
                  Creating your account...
                </span>
              ) : isPaidPlan ? (
                'Create Account'
              ) : (
                'Start Free Trial'
              )}
            </Button>
          </form>

          <div className="mt-5 text-center">
            <p className="text-sm text-gray-700 dark:text-gray-400">
              Already have an account?{' '}
              <Link to="/signin" className="text-brand-500 hover:text-brand-600 dark:text-brand-400 font-medium">
                Sign In
              </Link>
            </p>
          </div>
        </div>
      </div>

      {/* Desktop Pricing Panel - Renders in right side */}
      <div className="hidden lg:block">
        {/* This will be portaled to the right side */}
        {typeof document !== 'undefined' &&
          document.getElementById('signup-pricing-plans') &&
          ReactDOM.createPortal(
            <div className="space-y-6">
              {/* Billing Toggle - Centered with inline discount */}
              <div className="flex items-center justify-center gap-3 w-full max-w-[640px] mx-auto">
                <div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-xl shadow-sm">
                  <span
                    className={`absolute top-1/2 left-1 flex h-11 w-32 -translate-y-1/2 rounded-lg bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
                      billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-32'
                    }`}
                  ></span>
                  <button
                    type="button"
                    onClick={() => setBillingPeriod('monthly')}
                    className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
                      billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white'
                    }`}
                  >
                    Monthly
                  </button>
                  <button
                    type="button"
                    onClick={() => setBillingPeriod('annually')}
                    className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
                      billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white'
                    }`}
                  >
                    Annually
                  </button>
                </div>
                <p className={`inline-flex items-center gap-1.5 text-success-600 dark:text-success-400 text-sm font-semibold bg-success-50 dark:bg-success-900/20 px-3 py-1.5 rounded-full transition-opacity duration-200 ${
                  billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
                }`}>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Save up to {annualDiscountPercent}%
                </p>
              </div>

              {/* Plan Cards - Single column, stacked vertically */}
              <div className="grid gap-4 grid-cols-1 w-full max-w-[640px] mx-auto">
                {plans.map((plan) => {
                  const displayPrice = getDisplayPrice(plan);
                  const features = extractFeatures(plan);
                  const isSelected = selectedPlan?.id === plan.id;
                  const isFree = parseFloat(String(plan.price || 0)) === 0;
                  const isPopular = plan.slug.toLowerCase().includes('growth');

                  return (
                    <div
                      key={plan.id}
                      onClick={() => onPlanSelect(plan)}
                      className={`relative rounded-2xl p-5 cursor-pointer transition-all duration-300 ${
                        isSelected
                          ? 'border-[3px] border-success-500 bg-white dark:bg-gray-800 shadow-2xl ring-4 ring-success-500/20'
                          : isPopular
                          ? 'border-2 border-brand-200 dark:border-brand-800 bg-white dark:bg-gray-800/50 hover:shadow-xl'
                          : 'border-2 border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/50 hover:shadow-lg'
                      }`}
                    >
                      {isPopular && !isSelected && (
                        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                          <span className="bg-gradient-to-r from-success-500 to-success-500 text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg">
                            ⭐ POPULAR
                          </span>
                        </div>
                      )}
                      {isSelected && (
                        <div className="absolute -top-4 -right-4">
                          <div className="bg-brand-500 rounded-full p-2 shadow-lg">
                            <CheckCircleIcon className="w-8 h-8 text-white" />
                          </div>
                        </div>
                      )}
                      
                      {/* Header: Plan name, price, and features in horizontal layout */}
                      <div className="flex items-center gap-6">
                        {/* Plan Name & Price */}
                        <div className="flex-shrink-0 min-w-[200px]">
                          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-1">{plan.name}</h3>
                          <div className="flex items-baseline gap-1">
                            <span className="text-3xl font-bold text-gray-900 dark:text-white">
                              {isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
                            </span>
                            {!isFree && (
                              <span className="text-gray-500 dark:text-gray-400 text-sm">
                                {billingPeriod === 'annually' ? '/year' : '/month'}
                              </span>
                            )}
                          </div>
                          {billingPeriod === 'annually' && !isFree && (
                            <p className="text-gray-500 dark:text-gray-400 text-xs mt-0.5">
                              ${(displayPrice / 12).toFixed(2)}/month billed annually
                            </p>
                          )}
                        </div>
                        
                        {/* Features - 2 columns */}
                        <div className="flex-1 grid grid-cols-2 gap-x-6 gap-y-2.5">
                          {features.map((feature, idx) => (
                            <div key={idx} className="flex items-center gap-2">
                              <CheckCircleIcon className="w-4 h-4 text-success-500 dark:text-success-400 flex-shrink-0" />
                              <span className="text-sm text-gray-700 dark:text-gray-300 leading-tight">{feature}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>,
            document.getElementById('signup-pricing-plans')!
          )}
      </div>
    </div>
  );
}
