"use client";

import { useRouter } from "next/navigation";
import { useBookingStore } from "@/lib/booking-store";
import { usePaymentStore } from "@/lib/payment-store";
import { useMutation, useQuery } from "@tanstack/react-query";
import { apiClient } from "@/lib/api-client";
import { useState, useEffect } from "react";
import { PaymentMethod } from "@/types";
import { format } from "date-fns";
import {
  CreditCard,
  Smartphone,
  Wallet,
  Loader2,
  CheckCircle,
} from "lucide-react";

const getIconForMethod = (methodId: string) => {
  if (methodId.includes('CARD')) return CreditCard;
  if (methodId.includes('WALLET')) return Wallet;
  return Smartphone;
};

export default function PaymentPage() {
  const router = useRouter();
  const { bookingId, pnr, selectedSchedule, outboundSchedule, inboundSchedule, passengers, searchCriteria } = useBookingStore();
  const { selectedCurrency, setPaymentIntent, updateStatus } =
    usePaymentStore();
  const [selectedMethod, setSelectedMethod] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  const isRoundTrip = searchCriteria?.tripType === 'ROUND_TRIP';

  const { data: paymentMethods = [], isLoading: loadingMethods, error } = useQuery<PaymentMethod[]>({
    queryKey: ['paymentMethods'],
    queryFn: async () => {
      const response = await apiClient.get<PaymentMethod[]>('/payments/methods');
      return Array.isArray(response) ? response : [];
    },
  });

  // Calculate total amount
  const outboundBaseFare = isRoundTrip && outboundSchedule ? passengers.reduce(
    (sum) => sum + (outboundSchedule.baseFareAdult || 0),
    0,
  ) : 0;

  const inboundBaseFare = isRoundTrip && inboundSchedule ? passengers.reduce(
    (sum) => sum + (inboundSchedule.baseFareAdult || 0),
    0,
  ) : 0;

  const baseFare = isRoundTrip ? (outboundBaseFare + inboundBaseFare) : passengers.reduce(
    (sum) => sum + (selectedSchedule?.baseFareAdult || 0),
    0,
  );
  
  const totalAmount = baseFare;

  const paymentMutation = useMutation({
    mutationFn: async (data: any) => {
      // For TELEBIRR and WAAFI, use the initiate endpoint
      if (data.method === 'TELEBIRR' || data.method === 'WAAFI') {
        const response = await apiClient.post('/payments/initiate', {
          bookingId: data.bookingId,
          method: data.method,
          paymentMethodId: data.paymentMethodId,
          platform: 'web'
        });
        
        return response;
      }
      
      // For other payment methods, try the regular payment intent API
      try {
        return await apiClient.post("/payments/intent", data);
      } catch (error) {
        console.log("Payment API not available, using mock payment");
        // Mock payment response
        return {
          paymentIntentId: `mock-payment-${Date.now()}`,
          status: "PENDING",
          amountMinor: data.amountMinor,
          currency: data.currency,
          method: data.method,
        };
      }
    },
    onSuccess: async (data: any) => {
      // Handle TELEBIRR/WAAFI redirect response
      if ((selectedMethod === 'TELEBIRR' || selectedMethod === 'WAAFI') && data?.clientAction?.type === 'REDIRECT') {
        const redirectUrl = data.clientAction.url;
        
        // Store the intent ID for later verification
        setPaymentIntent(data.intentId);
        updateStatus("REQUIRES_ACTION");
        
        // Redirect to payment gateway
        window.location.href = redirectUrl;
        return;
      }
      
      setPaymentIntent(data.paymentIntentId || data.intentId);
      updateStatus("PROCESSING");

      // Simulate payment processing
      await new Promise((resolve) => setTimeout(resolve, 2000));

      updateStatus("SUCCEEDED");
      router.push("/booking/confirmation");
    },
    onError: (error: any) => {
      console.error("Payment failed:", error);
      updateStatus("FAILED");
      const errorMessage =
        error?.response?.data?.message ||
        error?.message ||
        "Payment failed. Please try again.";
      alert(errorMessage);
      setIsProcessing(false);
    },
  });



  const handlePayment = async () => {
    if (!selectedMethod || !bookingId) {
      alert("Please select a payment method");
      return;
    }

    setIsProcessing(true);

    // Find the selected payment method to get its ID
    const selectedPaymentMethod = paymentMethods.find(m => m.type === selectedMethod);
    
    if (!selectedPaymentMethod) {
      alert("Invalid payment method selected");
      setIsProcessing(false);
      return;
    }

    paymentMutation.mutate({
      bookingId,
      method: selectedMethod,
      paymentMethodId: selectedPaymentMethod.id,
      currency: selectedCurrency,
      amountMinor: totalAmount,
    });
  };

  // Redirect if no booking data (but not during navigation)
  useEffect(() => {
    // Add a small delay to allow state to be set from previous page
    const timer = setTimeout(() => {
      if (!bookingId || !pnr) {
        console.log(
          "Payment page: Missing booking data, redirecting to search",
        );
        console.log("bookingId:", bookingId, "pnr:", pnr);
        router.push("/booking/search");
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [bookingId, pnr, router]);

  if (!bookingId && !pnr) {
    return (
      <div className="min-h-screen bg-gray-50 py-12 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Loading payment details...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold mb-2 text-gray-900 dark:text-gray-100">
            Complete payment
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            Booking reference:{" "}
            <span className="font-bold text-primary">{pnr}</span>
          </p>

          {/* Payment Processing Overlay */}
          {isProcessing && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white dark:bg-gray-800 rounded-lg p-8 max-w-md text-center">
                {paymentMutation.isSuccess ? (
                  <>
                    <CheckCircle className="w-16 h-16 text-green-600 mx-auto mb-4" />
                    <h3 className="text-xl font-bold mb-2 text-gray-900 dark:text-gray-100">
                      Payment successful!
                    </h3>
                    <p className="text-gray-600 dark:text-gray-400 mb-4">
                      Redirecting to confirmation...
                    </p>
                    <Loader2 className="w-8 h-8 text-primary animate-spin mx-auto" />
                  </>
                ) : (
                  <>
                    <Loader2 className="w-16 h-16 text-primary animate-spin mx-auto mb-4" />
                    <h3 className="text-xl font-bold mb-2 text-gray-900 dark:text-gray-100">
                      Processing payment
                    </h3>
                    <p className="text-gray-600 dark:text-gray-400">
                      Please wait while we process your payment...
                    </p>
                  </>
                )}
              </div>
            </div>
          )}

          {/* Order Summary */}
          <div className="card mb-6">
            <h2 className="text-xl font-semibold mb-6 text-gray-900 dark:text-gray-100">
              Order summary
            </h2>
            <div className="space-y-6">
              {isRoundTrip ? (
                <>
                  {/* Outbound Journey */}
                  <div>
                    <div className="flex items-center gap-2 mb-4">
                      <div className="w-2 h-2 bg-primary rounded-full" />
                      <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Outbound Journey</span>
                      <span className="ml-auto text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full font-medium">
                        {outboundSchedule?.selectedSeatClassName?.replace(/_/g, ' ') || 'Standard'}
                      </span>
                    </div>
                    
                    {/* Flight-style timeline */}
                    <div className="flex">
                      {/* Left column: Timeline with dots and line */}
                      <div className="flex flex-col items-center w-8 flex-shrink-0">
                        {/* Origin dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-primary bg-white dark:bg-gray-900 z-10" />
                        {/* Vertical line */}
                        <div className="w-0.5 flex-1 bg-gradient-to-b from-primary via-gray-300 dark:via-gray-700 to-gray-300 dark:to-gray-700 my-2" />
                        {/* Destination dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-gray-400 dark:border-gray-600 bg-white dark:bg-gray-900 z-10" />
                      </div>
                      
                      {/* Right column: Content */}
                      <div className="flex-1 flex flex-col">
                        {/* Origin */}
                        <div className="pb-8">
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {outboundSchedule?.departureTime ? format(new Date(outboundSchedule.departureTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {outboundSchedule?.departureTime ? format(new Date(outboundSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {outboundSchedule?.origin}
                          </div>
                        </div>

                        {/* Journey Info */}
                        <div className="pb-8">
                          <div className="flex items-center gap-6 text-sm text-gray-600 dark:text-gray-400">
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                              <span className="font-medium">{outboundSchedule?.duration}</span>
                            </div>
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                              </svg>
                              <span className="font-medium">Train {outboundSchedule?.trainNumber}</span>
                            </div>
                          </div>
                        </div>

                        {/* Destination */}
                        <div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {outboundSchedule?.arrivalTime ? format(new Date(outboundSchedule.arrivalTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {outboundSchedule?.arrivalTime ? format(new Date(outboundSchedule.arrivalTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {outboundSchedule?.destination}
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="mt-4 pt-3 border-t border-gray-100 dark:border-gray-800">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600 dark:text-gray-400">Outbound fare</span>
                        <span className="font-semibold text-gray-900 dark:text-gray-100">ETB {(outboundBaseFare / 100).toFixed(2)}</span>
                      </div>
                    </div>
                  </div>

                  {/* Return Journey */}
                  <div className="pt-4 border-t-2 border-dashed border-gray-200 dark:border-gray-700">
                    <div className="flex items-center gap-2 mb-4">
                      <div className="w-2 h-2 bg-blue-500 rounded-full" />
                      <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Return Journey</span>
                      <span className="ml-auto text-xs px-2 py-0.5 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-full font-medium">
                        {inboundSchedule?.selectedSeatClassName?.replace(/_/g, ' ') || 'Standard'}
                      </span>
                    </div>
                    
                    {/* Flight-style timeline */}
                    <div className="flex">
                      {/* Left column: Timeline with dots and line */}
                      <div className="flex flex-col items-center w-8 flex-shrink-0">
                        {/* Origin dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-blue-500 bg-white dark:bg-gray-900 z-10" />
                        {/* Vertical line */}
                        <div className="w-0.5 flex-1 bg-gradient-to-b from-blue-500 via-gray-300 dark:via-gray-700 to-gray-300 dark:to-gray-700 my-2" />
                        {/* Destination dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-gray-400 dark:border-gray-600 bg-white dark:bg-gray-900 z-10" />
                      </div>
                      
                      {/* Right column: Content */}
                      <div className="flex-1 flex flex-col">
                        {/* Origin */}
                        <div className="pb-8">
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {inboundSchedule?.departureTime ? format(new Date(inboundSchedule.departureTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {inboundSchedule?.departureTime ? format(new Date(inboundSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {inboundSchedule?.origin}
                          </div>
                        </div>

                        {/* Journey Info */}
                        <div className="pb-8">
                          <div className="flex items-center gap-6 text-sm text-gray-600 dark:text-gray-400">
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                              <span className="font-medium">{inboundSchedule?.duration}</span>
                            </div>
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                              </svg>
                              <span className="font-medium">Train {inboundSchedule?.trainNumber}</span>
                            </div>
                          </div>
                        </div>

                        {/* Destination */}
                        <div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {inboundSchedule?.arrivalTime ? format(new Date(inboundSchedule.arrivalTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {inboundSchedule?.arrivalTime ? format(new Date(inboundSchedule.arrivalTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {inboundSchedule?.destination}
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="mt-4 pt-3 border-t border-gray-100 dark:border-gray-800">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600 dark:text-gray-400">Return fare</span>
                        <span className="font-semibold text-gray-900 dark:text-gray-100">ETB {(inboundBaseFare / 100).toFixed(2)}</span>
                      </div>
                    </div>
                  </div>
                </>
              ) : (
                <>
                  {/* One-Way Journey */}
                  <div>
                    <div className="flex items-center gap-2 mb-4">
                      <div className="w-2 h-2 bg-primary rounded-full" />
                      <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Your Journey</span>
                      <span className="ml-auto text-xs px-2 py-0.5 bg-primary/10 text-primary rounded-full font-medium">
                        {selectedSchedule?.selectedSeatClassName?.replace(/_/g, ' ') || 'Standard'}
                      </span>
                    </div>
                    
                    {/* Flight-style timeline */}
                    <div className="flex">
                      {/* Left column: Timeline with dots and line */}
                      <div className="flex flex-col items-center w-8 flex-shrink-0">
                        {/* Origin dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-primary bg-white dark:bg-gray-900 z-10" />
                        {/* Vertical line */}
                        <div className="w-0.5 flex-1 bg-gradient-to-b from-primary via-gray-300 dark:via-gray-700 to-gray-300 dark:to-gray-700 my-2" />
                        {/* Destination dot */}
                        <div className="w-4 h-4 rounded-full border-4 border-gray-400 dark:border-gray-600 bg-white dark:bg-gray-900 z-10" />
                      </div>
                      
                      {/* Right column: Content */}
                      <div className="flex-1 flex flex-col">
                        {/* Origin */}
                        <div className="pb-8">
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {selectedSchedule?.departureTime ? format(new Date(selectedSchedule.departureTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {selectedSchedule?.departureTime ? format(new Date(selectedSchedule.departureTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {selectedSchedule?.origin}
                          </div>
                        </div>

                        {/* Journey Info */}
                        <div className="pb-8">
                          <div className="flex items-center gap-6 text-sm text-gray-600 dark:text-gray-400">
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                              <span className="font-medium">{selectedSchedule?.duration}</span>
                            </div>
                            <div className="flex items-center gap-1.5">
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                              </svg>
                              <span className="font-medium">Train {selectedSchedule?.trainNumber}</span>
                            </div>
                          </div>
                        </div>

                        {/* Destination */}
                        <div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white">
                            {selectedSchedule?.arrivalTime ? format(new Date(selectedSchedule.arrivalTime), 'HH:mm') : '--:--'}
                          </div>
                          <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                            {selectedSchedule?.arrivalTime ? format(new Date(selectedSchedule.arrivalTime), 'EEE, MMM d') : 'N/A'}
                          </div>
                          <div className="text-base font-semibold text-gray-900 dark:text-white mt-2">
                            {selectedSchedule?.destination}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </>
              )}
              
              {/* Passengers and Total */}
              <div className="pt-4 border-t-2 border-gray-200 dark:border-gray-700">
                <div className="flex justify-between text-sm mb-3">
                  <span className="text-gray-600 dark:text-gray-400">
                    Passengers
                  </span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {passengers.length} passenger{passengers.length !== 1 ? "s" : ""}
                  </span>
                </div>
                <div className="flex justify-between items-center pt-3 border-t border-gray-200 dark:border-gray-700">
                  <span className="text-base font-bold text-gray-900 dark:text-gray-100">
                    Total amount
                  </span>
                  <span className="text-2xl font-bold text-primary dark:text-gray-100">
                    ETB {(totalAmount / 100).toFixed(2)}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Payment Methods */}
          <div className="card mb-6">
            <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-gray-100">
              Select payment method
            </h2>
            {loadingMethods ? (
              <div className="flex justify-center py-8">
                <Loader2 className="w-8 h-8 text-primary animate-spin" />
                <p className="ml-2 text-gray-600 dark:text-gray-400">Loading payment methods...</p>
              </div>
            ) : error ? (
              <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                <p className="text-red-800 dark:text-red-200 text-sm">
                  Failed to load payment methods. Please refresh the page.
                </p>
              </div>
            ) : paymentMethods.length === 0 ? (
              <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
                <p className="text-yellow-800 dark:text-yellow-200 text-sm">
                  No payment methods available at the moment.
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                {paymentMethods.map((method) => {
                  const Icon = getIconForMethod(method.type);
                  const isSelected = selectedMethod === method.type;
                  return (
                    <button
                      key={method.id}
                      onClick={() => setSelectedMethod(method.type)}
                      disabled={isProcessing || !method.enabled}
                      className={`w-full p-4 rounded-lg border-2 transition-all text-left ${
                        isSelected
                          ? "border-primary bg-primary/10 dark:bg-primary/20 shadow-md"
                          : "border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-primary dark:hover:border-primary"
                      } ${isProcessing || !method.enabled ? "opacity-50 cursor-not-allowed" : ""}`}
                    >
                      <div className="flex items-center gap-3">
                        <div
                          className={`w-12 h-12 rounded-lg flex items-center justify-center ${
                            isSelected
                              ? "bg-primary"
                              : "bg-gray-100 dark:bg-gray-700"
                          }`}
                        >
                          <Icon
                            className={`w-6 h-6 ${isSelected ? "text-white" : "text-primary"}`}
                          />
                        </div>
                        <div className="flex-1">
                          <p className="font-semibold text-gray-900 dark:text-gray-100">
                            {method.displayName}
                          </p>
                          <p className="text-sm text-gray-600 dark:text-gray-400">
                            {method.region} · {method.currency}
                          </p>
                        </div>
                        {isSelected && (
                          <div className="w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                            <CheckCircle className="w-5 h-5 text-white" />
                          </div>
                        )}
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {/* Action Buttons */}
          <div className="flex flex-col gap-3">
            <button
              onClick={handlePayment}
              disabled={!selectedMethod || isProcessing}
              className={`btn-primary w-full py-4 text-lg font-semibold ${
                !selectedMethod || isProcessing
                  ? "opacity-50 cursor-not-allowed"
                  : ""
              }`}
            >
              {isProcessing ? (
                <span className="flex items-center justify-center gap-2">
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Processing...
                </span>
              ) : (
                `Pay ETB ${(totalAmount / 100).toFixed(2)}`
              )}
            </button>

            <button
              onClick={() => router.back()}
              disabled={isProcessing}
              className="btn-secondary w-full py-2"
            >
              Back to review
            </button>
          </div>

          {/* Error Message */}
          {paymentMutation.isError && (
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mt-4">
              <p className="text-red-800 dark:text-red-200 text-sm font-medium">
                ⚠️ Payment failed. Please try again or contact support if the
                problem persists.
              </p>
            </div>
          )}

          {/* Security Notice */}
          <div className="mt-6 p-4 bg-gray-100 dark:bg-gray-800 rounded-lg">
            <p className="text-xs text-gray-600 dark:text-gray-400 text-center">
              🔒 Your payment is secure and encrypted. We do not store your
              payment information.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
