"use client";

import { useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { useLanguage } from '@/src/lib/context/LanguageContext';
import { getLocalizedUrl } from '@/src/lib/utils/urlHelper';

interface PayPalFormProps {
  amount?: number | null;
  submissionId?: string;
}

export default function PayPalForm({ amount, submissionId }: PayPalFormProps) {
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  // A hard redirect leaves the router behind, so the language and tenant have
  // to be written into the URL by hand or the customer finishes paying on a
  // French site and lands on an English thank-you page.
  const { currentLanguage } = useLanguage();
  const franchiseeId = useSearchParams().get('franchiseeId');

  const formatAmount = (amt: number | null | undefined): string => {
    if (!amt) return '$25.00';
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(amt);
  };

  const handlePayPalPayment = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setErrorMsg(null);

    try {
      // Dummy PayPal payment logic
      console.log('[PayPal] Processing payment with dummy implementation');
      
      // Simulate API call delay
      await new Promise(resolve => setTimeout(resolve, 2000));

      // Simulate success
      console.log('[PayPal] Payment processed successfully');
      window.location.href = getLocalizedUrl(
        `/thank-you/${submissionId || 'default'}`,
        currentLanguage,
        franchiseeId,
      );
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Payment failed';
      setErrorMsg(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handlePayPalPayment} className="space-y-6">
      {/* Error Message */}
      {errorMsg && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
          {errorMsg}
        </div>
      )}

      {/* PayPal Dummy Form */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2 font-[Signika]">
            Email Address
          </label>
          <input
            type="email"
            placeholder="your.email@example.com"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0097DC] focus:border-transparent"
            required
          />
        </div>

        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2 font-[Signika]">
            Password
          </label>
          <input
            type="password"
            placeholder="••••••••"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0097DC] focus:border-transparent"
            required
          />
        </div>

        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <p className="text-xs text-blue-700 font-[Signika]">
            💡 This is a demo. Use any email/password to continue.
          </p>
        </div>
      </div>

      {/* Payment Button */}
      <button
        type="submit"
        disabled={loading}
        className="w-full bg-gradient-to-r from-[#003087] to-[#009cde] hover:from-[#002456] hover:to-[#007da8] text-white font-bold py-4 px-6 rounded-full text-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-lg hover:shadow-xl"
      >
        {loading ? 'Processing Payment...' : `Pay with PayPal - ${formatAmount(amount)}`}
      </button>

      {/* Info Text */}
      <p className="text-sm text-gray-500 text-center">
        Your payment is secure. You will be redirected to PayPal to complete payment.
      </p>
    </form>
  );
}
