"use client";

import React, { useState, useEffect } from "react";
import { loadStripe } from "@stripe/stripe-js";
import {
  Elements,
  CardElement,
  useStripe,
  useElements,
} from "@stripe/react-stripe-js";
import { toast } from "sonner";
import { useOnboarding } from "../context/OnboardingContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Loader2, Lock, ChevronLeft } from "lucide-react";

const stripePromise = loadStripe(
  process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY || "pn-sdf",
);

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000";

interface Plan {
  _id: string;
  name: string;
  trialDays?: number;
  price?: { monthly: number; yearly: number };
}

interface BillingAddress {
  street: string;
  city: string;
  state: string;
  postalCode: string;
  country: string;
  country_code:string
}

interface PaymentFormProps {
  selectedPlan: string | null;
  billingPeriod: "monthly" | "yearly";
  organizationData: any;
  userData: any;
  plans: Plan[];
  onBack: () => void;
  onNext: () => void;
  setSignupResult: (result: any) => void;
  setLoading: (loading: boolean) => void;
}

async function apiFetch(path: string, options: RequestInit = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(options.headers || {}),
    },
    credentials: "include",
  });

  const data = await res.json();

  if (!res.ok) {
    throw new Error(data?.message || `Request failed: ${res.status}`);
  }

  return data;
}

const Field = ({
  label,
  required,
  children,
}: {
  label: string;
  required?: boolean;
  children: React.ReactNode;
}) => (
  <div className="space-y-1.5">
    <Label className="text-sm font-semibold text-gray-700">
      {label} {required && <span className="text-rose-500">*</span>}
    </Label>
    {children}
  </div>
);

function StripePaymentForm({
  selectedPlan,
  billingPeriod,
  organizationData,
  userData,
  plans,
  onBack,
  onNext,
  setSignupResult,
  setLoading,
}: PaymentFormProps) {
  const stripe = useStripe();
  const elements = useElements();
  const { organizationData: ctxOrgData,updateLead } = useOnboarding();

  const [processing, setProcessing] = useState(false);
  const [clientSecret, setClientSecret] = useState("");
  const [amount, setAmount] = useState(0);
  const [intentLoading, setIntentLoading] = useState(true);

  const [billingAddress, setBillingAddress] = useState<BillingAddress>({
    street: ctxOrgData?.address?.street || "",
    city: ctxOrgData?.address?.city || "",
    state: ctxOrgData?.address?.state || "",
    postalCode: ctxOrgData?.address?.zipCode || "",
    country: ctxOrgData?.address?.country || "IN",
    country_code: ctxOrgData?.address?.country_code ||"IN",
  });

  const planData = plans.find((p) => p._id === selectedPlan);
  const planName = planData?.name || "Pro Plan";
  const trialDays = planData?.trialDays || 0;

  useEffect(() => {
    if (planData) {
      setAmount(
        billingPeriod === "yearly"
          ? (planData.price?.yearly ?? 0)
          : (planData.price?.monthly ?? 0),
      );
    }
  }, [planData, billingPeriod]);

  useEffect(() => {
    if (!selectedPlan || !billingPeriod || !organizationData || !userData)
      return;

    const createPaymentIntent = async () => {
      setIntentLoading(true);
      try {
        const response = await apiFetch("/client/create-payment-intent", {
          method: "POST",
          body: JSON.stringify({
            planId: selectedPlan,
            billingPeriod,
            organizationData,
            userData,
            createDefaultChatbot: true,
          }),
        });

        if (response.success && response.data?.clientSecret) {
          setClientSecret(response.data.clientSecret);
        } else {
          throw new Error(
            response.data?.message || "Failed to create payment intent",
          );
        }
      } catch (error: any) {
        toast.error(`Payment setup failed: ${error.message}`);
      } finally {
        setIntentLoading(false);
      }
    };

    createPaymentIntent();
  }, [selectedPlan, billingPeriod, organizationData, userData]);

  const validateBillingAddress = () => {
    if (!billingAddress.street.trim()) {
      toast.error("Street address is required");
      return false;
    }
    if (!billingAddress.city.trim()) {
      toast.error("City is required");
      return false;
    }
    if (!billingAddress.state.trim()) {
      toast.error("State is required");
      return false;
    }
    if (!billingAddress.postalCode.trim()) {
      toast.error("Postal code is required");
      return false;
    }
    return true;
  };

  console.log("userData",userData)

  const handlePayment = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) {
      toast.error("Stripe not loaded");
      return;
    }
    if (!clientSecret) {
      toast.error("Payment setup incomplete. Please wait…");
      return;
    }
    if (!validateBillingAddress()) return;

    const cardElement = elements.getElement(CardElement);
    if (!cardElement) {
      toast.error("Card element not found");
      return;
    }

    setProcessing(true);
    setLoading(true);

    try {
      const { error, paymentIntent } = await stripe.confirmCardPayment(
        clientSecret,
        {
          payment_method: {
            card: cardElement,
            billing_details: {
              name: `${userData?.firstName} ${userData?.lastName}`.trim(),
              email: userData?.email,
              address: {
                line1: billingAddress.street,
                city: billingAddress.city,
                state: billingAddress.state,
                postal_code: billingAddress.postalCode,
                country: billingAddress.country_code,
              },
            },
          },
        },
      );

      if (error) {
        toast.error(error.message || "Payment failed");
        return;
      }

      if (paymentIntent?.status !== "succeeded") {
        throw new Error(`Unexpected payment status: ${paymentIntent?.status}`);
      }

      const signupResponse = await apiFetch("/client/complete-signup", {
        method: "POST",
        body: JSON.stringify({
          paymentIntentId: paymentIntent.id,
          organizationData,
          userData,
          billingAddress,
          planId: selectedPlan,
          billingPeriod,
          createDefaultChatbot: true,
        }),
      });

      if (!signupResponse.success) {
        throw new Error(signupResponse.message || "Signup failed");
      }

      toast.success("Payment successful! Your organization is ready 🎉");
      setSignupResult(signupResponse.data);
       const success = await updateLead({
         status: "signup_completed",
         paymentData: {
           paymentIntentId: paymentIntent.id,
         },
       });
      onNext();
    } catch (error: any) {
      toast.error(error.message || "Payment failed");
    } finally {
      setProcessing(false);
      setLoading(false);
    }
  };

  const cardElementOptions = {
    hidePostalCode: true,
    style: {
      base: {
        fontSize: "14px",
        color: "#1f2937",
        fontSmoothing: "antialiased",
        "::placeholder": { color: "#9ca3af" },
      },
      invalid: { color: "#ef4444" },
    },
  };

  return (
    <div className="w-full mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">
          Complete Your Payment
        </h1>
        <p className="text-gray-500">
          Secure payment powered by Stripe. Your card data is encrypted and
          never stored.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-2">
        <div className="lg:col-span-2">
          {intentLoading ? (
            <div className="flex items-center justify-center py-20 gap-3 text-gray-500">
              <Loader2 className="w-5 h-5 animate-spin" />
              <span className="text-sm font-medium">Setting up payment…</span>
            </div>
          ) : (
            <div className="bg-white rounded-2xl border border-gray-200 p-4">
              {/* Organization Information Section */}
              <div className="mb-6 pb-6 border-b border-gray-200">
                <h3 className="text-sm font-bold text-gray-900 mb-2 flex items-center gap-2">
                  🏢 Organization Information
                </h3>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  <div className="bg-gray-50 rounded-lg p-1">
                    <p className="text-xs text-gray-400 uppercase mb-1">
                      Organization Name
                    </p>
                    <p className="text-sm font-semibold text-gray-900">
                      {organizationData?.name || "—"}
                    </p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-1">
                    <p className="text-xs text-gray-400 uppercase mb-1">
                      Organization Email
                    </p>
                    <p className="text-sm font-semibold text-gray-900 break-all">
                      {organizationData?.email || "—"}
                    </p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-1">
                    <p className="text-xs text-gray-400 uppercase mb-1">
                      Phone
                    </p>
                    <p className="text-sm font-semibold text-gray-900">
                      {organizationData?.phone || "—"}
                    </p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-1">
                    <p className="text-xs text-gray-400 uppercase mb-1">
                      Website
                    </p>
                    <p className="text-sm font-semibold text-gray-900 truncate">
                      {organizationData?.website || "—"}
                    </p>
                  </div>
                </div>
              </div>

              {/* Billing Address Section */}
              <div>
                <h2 className="text-base font-bold text-gray-900 mb-1 flex items-center gap-1">
                  📍 Billing Address
                </h2>

                <div className="space-y-2">
                  <Field label="Street Address">
                    <Input
                      disabled
                      value={billingAddress.street}
                      placeholder="123 Main Street"
                      className="bg-gray-100 text-gray-700 cursor-not-allowed border-gray-300"
                    />
                  </Field>

                  <div className="grid grid-cols-2 gap-2">
                    <Field label="City">
                      <Input
                        disabled
                        value={billingAddress.city}
                        placeholder="Mumbai"
                        className="bg-gray-100 text-gray-700 cursor-not-allowed border-gray-300"
                      />
                    </Field>
                    <Field label="State">
                      <Input
                        disabled
                        value={billingAddress.state}
                        placeholder="Maharashtra"
                        className="bg-gray-100 text-gray-700 cursor-not-allowed border-gray-300"
                      />
                    </Field>
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <Field label="Country">
                      <Input
                        disabled
                        value={billingAddress.country}
                        className="bg-gray-100 text-gray-700 cursor-not-allowed border-gray-300"
                      />
                    </Field>
                    <Field label="Postal / ZIP Code">
                      <Input
                        disabled
                        value={billingAddress.postalCode}
                        className="bg-gray-100 text-gray-700 cursor-not-allowed border-gray-300"
                      />
                    </Field>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="lg:col-span-1 flex flex-col gap-2">
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden sticky top-6">
            <div className="px-6 py-4 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider">
                Order Summary
              </span>
              {trialDays > 0 && (
                <Badge className="bg-emerald-100 text-emerald-700 border-emerald-200 text-xs">
                  {trialDays}-day trial
                </Badge>
              )}
            </div>

            <div className="px-4 py-3">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <p className="font-semibold text-gray-900">{planName}</p>
                </div>
                <div className="text-right">
                  <p className="text-2xl font-bold text-gray-900">
                    ${amount.toLocaleString()}
                  </p>
                  <p className="text-xs text-gray-400">
                    per/{billingPeriod === "yearly" ? "year" : "month"}
                  </p>
                </div>
              </div>

              {/* <div className="border-t border-gray-100 pt-4 space-y-3">
                {[
                  // { label: "Organization", val: organizationData?.name },
                  // { label: "Admin Email", val: userData?.email },
                  { label: "Currency", val: "USD" },
                ].map(({ label, val }) => (
                  <div key={label} className="flex justify-between text-sm">
                    <span className="text-gray-500">{label}</span>
                    <span className="font-medium text-gray-900 truncate max-w-[160px] text-right">
                      {val || "—"}
                    </span>
                  </div>
                ))}
              </div> */}
            </div>

            <div className="px-6 py-4 bg-blue-600 flex items-center justify-between">
              <span className="text-sm font-semibold text-blue-100">
                Total Amount
              </span>
              <span className="text-xl font-bold text-white">
                {trialDays > 0 ? "Free" : `$${amount.toLocaleString()}`}
              </span>
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-gray-200 p-6">
            <h2 className="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
              💳 Card Details
            </h2>

            <div className="border-2 border-gray-200 rounded-xl p-4 focus-within:border-blue-500 focus-within:ring-2 focus-within:ring-blue-100 transition-all">
              <CardElement options={cardElementOptions} />
            </div>
          </div>

          <form onSubmit={handlePayment} className="flex gap-3">
            <Button
              type="button"
              variant="outline"
              disabled={processing}
              onClick={onBack}
              className="flex-1 rounded-xl cursor-pointer gap-2"
            >
              <ChevronLeft className="w-4 h-4" /> Back
            </Button>
            <Button
              type="submit"
              disabled={!stripe || !elements || processing || !clientSecret}
              className="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl cursor-pointer gap-2 shadow-lg shadow-blue-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {processing ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Processing…
                </>
              ) : (
                <>
                  <Lock className="w-4 h-4" />
                  Pay ${amount.toLocaleString()}
                </>
              )}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default function Step4Payment({
  selectedPlan,
  billingPeriod,
  organizationData,
  userData,
  plans = [],
  onBack,
  onNext,
  setSignupResult,
  setLoading,
}: PaymentFormProps) {
  const [stripeReady, setStripeReady] = useState(false);

 

  useEffect(() => {
    stripePromise.then(() => setStripeReady(true));
  }, []);

  if (!stripeReady) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-3 text-gray-500">
        <div className="w-9 h-9 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
        <p className="text-sm font-medium">Loading payment gateway…</p>
      </div>
    );
  }

  return (
    <Elements stripe={stripePromise}>
      <StripePaymentForm
        selectedPlan={selectedPlan}
        billingPeriod={billingPeriod}
        organizationData={organizationData}
        userData={userData}
        plans={plans}
        onBack={onBack}
        onNext={onNext}
        setSignupResult={setSignupResult}
        setLoading={setLoading}
      />
    </Elements>
  );
}
