'use client';

import React, { useState } from 'react';
import { PayPalScriptProvider, PayPalButtons } from '@paypal/react-paypal-js';
import { ShieldCheck, Lock, AlertCircle, Loader2 } from 'lucide-react';
import { apiRequest } from '@/lib/api';
import { toast } from '@/context/ToastContext';

interface PayPalPaymentFormProps {
  clientId: string;
  courseId: string;
  courseTitle: string;
  lessons?: string[];
  studentName: string;
  email: string;
  whatsappNumber: string;
  amount: number;
  currency?: string;
  onSuccess: (orderId: string) => void;
  onError: (errorMsg: string) => void;
  onCancel?: () => void;
}

export default function PayPalPaymentForm({
  clientId,
  courseId,
  courseTitle,
  lessons = [],
  studentName,
  email,
  whatsappNumber,
  amount,
  currency = 'EUR',
  onSuccess,
  onError,
  onCancel,
}: PayPalPaymentFormProps) {
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  if (!clientId) {
    return (
      <div className="p-4 rounded-xl bg-amber-50 border border-amber-200 text-amber-900 text-xs font-semibold flex items-start gap-2">
        <AlertCircle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
        <span>
          PayPal Client ID is not configured in system settings. Please contact admin to enable PayPal payments.
        </span>
      </div>
    );
  }

  const handleCreateOrder = async () => {
    if (!studentName.trim() || !email.trim() || !whatsappNumber.trim()) {
      toast.error('Please complete all required contact fields before paying with PayPal.');
      throw new Error('Required contact details missing');
    }
    if (!courseId) {
      toast.error('Please select a course.');
      throw new Error('Course selection missing');
    }
    setLoading(true);
    setErrorMessage(null);
    try {
      const res = await apiRequest('/payments/paypal/create-order', {
        method: 'POST',
        body: JSON.stringify({
          courseId,
          lessons,
          amount,
        }),
      });

      if (res.success && res.paypalOrderId) {
        return res.paypalOrderId;
      }
      throw new Error(res.error || 'Failed to initialize PayPal order session.');
    } catch (err: any) {
      const msg = err.message || 'Error creating PayPal payment order.';
      setErrorMessage(msg);
      onError(msg);
      setLoading(false);
      throw err;
    }
  };

  const handleApprove = async (data: any) => {
    setLoading(true);
    setErrorMessage(null);
    try {
      const res = await apiRequest('/payments/paypal/capture-order', {
        method: 'POST',
        body: JSON.stringify({
          paypalOrderId: data.orderID,
          courseId,
          lessons,
          studentName,
          email,
          whatsappNumber,
          amount,
        }),
      });

      if (res.success && res.orderId) {
        onSuccess(res.orderId);
      } else {
        const msg = res.error || 'Payment capture failed.';
        setErrorMessage(msg);
        onError(msg);
        setLoading(false);
      }
    } catch (err: any) {
      const msg = err.message || 'Error capturing PayPal transaction.';
      setErrorMessage(msg);
      onError(msg);
      setLoading(false);
    }
  };

  const handleError = (err: any) => {
    const msg = err?.message || 'PayPal transaction was cancelled or encountered an error.';
    setErrorMessage(msg);
    onError(msg);
    setLoading(false);
  };

  return (
    <PayPalScriptProvider
      options={{
        clientId: clientId,
        currency: currency.toUpperCase(),
        intent: 'capture',
      }}
    >
      <div className="space-y-3 pt-1">
        {errorMessage && (
          <div className="p-3.5 rounded-xl bg-red-50 border border-red-200 text-red-700 text-xs font-semibold flex items-start gap-2 animate-fadeIn">
            <AlertCircle className="w-4 h-4 text-red-600 shrink-0 mt-0.5" />
            <span>{errorMessage}</span>
          </div>
        )}

        {loading && (
          <div className="py-4 text-center space-y-2">
            <Loader2 className="w-6 h-6 animate-spin mx-auto text-[#FFC700]" />
            <p className="text-xs font-bold text-gray-700">Processing PayPal Payment...</p>
          </div>
        )}

        <div className={loading ? 'opacity-40 pointer-events-none' : ''}>
          <PayPalButtons
            style={{
              layout: 'vertical',
              color: 'gold',
              shape: 'rect',
              label: 'pay',
              height: 48,
            }}
            createOrder={handleCreateOrder}
            onApprove={handleApprove}
            onError={handleError}
            onCancel={() => {
              setLoading(false);
            }}
          />
        </div>

        <div className="flex items-center justify-between text-xs text-gray-500 font-medium px-1">
          <span className="flex items-center gap-1">
            <ShieldCheck className="w-4 h-4 text-emerald-600" /> Official PayPal Gateway
          </span>
          <span className="flex items-center gap-1">
            <Lock className="w-3.5 h-3.5 text-gray-400" /> Buyer Protection Included
          </span>
        </div>
      </div>
    </PayPalScriptProvider>
  );
}
