"use client"
import { useState } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Zap, Plus, Loader2, Phone, MessageSquare, Info } from "lucide-react"
import { useGetTopupPlans, usePurchaseTopup, useGetCreditRates } from "@/lib/react-query/hooks/topups"
import { TopupCardSkeleton } from "./SubscriptionSkeleton"
import { StripePaymentModal } from "./StripePaymentModal"
import type { TopupPlan } from "@/types/topups"
import { queryClient } from "@/lib/react-query/client"
import { formatCurrency } from "@/lib/utils"
import { getUserTopupCreditsBalance, getUserTopUpTransactions } from "@/lib/react-query/queries/topups"
import { useTranslations } from "next-intl"

interface TopupCardProps {
  topup: TopupPlan
  onPurchase: (topupId: string) => void
  isPurchasing: boolean
  purchasingTopupId: string | null
}

function TopupCard({ topup, onPurchase, isPurchasing, purchasingTopupId }: TopupCardProps) {
  const t = useTranslations("credits.topups")

  const isThisTopupPurchasing = purchasingTopupId === topup._id
  const pricePerCredit = (topup.amountPaid / topup.credits).toFixed(2)

  return (
    <Card className="relative overflow-hidden transition-all hover:border-primary/50 hover:shadow-lg group">
      {/* Gradient accent line at top */}
      <div className="absolute top-0 left-0 right-0 h-1 bg-linear-to-r from-primary to-primary/60" />

      <CardContent className="p-6 space-y-5">
        {/* Header with name and badge */}
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-linear-to-br from-primary/20 to-primary/5 flex items-center justify-center group-hover:scale-105 transition-transform">
              <Zap className="w-6 h-6 text-primary" />
            </div>
            <div>
              <h3 className="font-semibold text-gray-900">{topup.name}</h3>
              <p className="text-xs text-gray-500">{t("oneTimePurchase")}</p>
            </div>
          </div>
        </div>

        {/* Credits Display - Main Focus */}
        <div className="text-center py-4 bg-linear-to-br from-primary/5 to-transparent rounded-xl border border-primary/10">
          <div className="flex items-baseline justify-center gap-1">
            <span className="text-5xl font-bold text-primary">{topup.credits}</span>
            <span className="text-lg text-gray-500">crédits</span>
          </div>
          {/* <p className="text-sm text-gray-500 mt-1">{formatCurrency(+pricePerCredit)} {t("perCredit")}</p> */}
        </div>

        {/* Price and Purchase Button */}
        <div className="space-y-3">
          <div className="flex items-center justify-between px-1">
            <span className="text-sm text-gray-600">{t("totalPrice")}</span>
            <span className="text-2xl font-bold text-gray-900">{formatCurrency(topup.amountPaid)}</span>
          </div>

          <Button
            onClick={() => onPurchase(topup._id)}
            disabled={isPurchasing}
            className="w-full bg-primary-gradient hover:bg-primary/90 text-white h-11"
          >
            {isThisTopupPurchasing ? (
              <div className="flex items-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                {t("processing")}
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <Plus className="w-4 h-4" />
                {t("buyNow")}
              </div>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

export function TopupsList() {
  const t = useTranslations("credits.topups")

  const { data: topups, isLoading } = useGetTopupPlans()
  const { data: creditRates } = useGetCreditRates()
  const purchaseTopupMutation = usePurchaseTopup()

  const [isPaymentModalOpen, setIsPaymentModalOpen] = useState(false)
  const [clientSecret, setClientSecret] = useState<string | null>(null)
  const [selectedTopup, setSelectedTopup] = useState<TopupPlan | null>(null)
  const [purchasingTopupId, setPurchasingTopupId] = useState<string | null>(null)

  const handlePurchase = async (topup: TopupPlan) => {
    setPurchasingTopupId(topup._id)
    try {
      const response = await purchaseTopupMutation.mutateAsync({ topupPlanId: topup._id })
      setClientSecret(response.clientSecret)
      setSelectedTopup(topup)
      setIsPaymentModalOpen(true)
    } catch (error) {
      console.error("Failed to initiate purchase:", error)
    } finally {
      setPurchasingTopupId(null)
    }
  }

  const handlePaymentSuccess = () => {
    // Refresh subscription data to show updated credits
    queryClient.invalidateQueries({ queryKey: getUserTopupCreditsBalance })
    queryClient.invalidateQueries({ queryKey: getUserTopUpTransactions })
    setClientSecret(null)
    setSelectedTopup(null)
  }

  const handleCloseModal = () => {
    setIsPaymentModalOpen(false)
    setClientSecret(null)
    setSelectedTopup(null)
  }

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {[...Array(3)].map((_, i) => (
          <TopupCardSkeleton key={i} />
        ))}
      </div>
    )
  }

  if (!topups || topups.length === 0) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="text-center py-8">
            <Zap className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">{t("noTopups.title")}</h3>
            <p className="text-gray-600">{t("noTopups.description")}</p>
          </div>
        </CardContent>
      </Card>
    )
  }


  // Filter only active topups
  const activeTopups = topups.filter(topup => topup.isActive)

  return (
    <>
      {creditRates && creditRates.length > 0 && (
        <div className="mb-6 flex flex-wrap gap-4 items-center bg-blue-50/50 border border-blue-100 p-4 rounded-xl">
          <div className="flex items-center gap-2 text-blue-900 font-medium shrink-0">
            <Info className="w-5 h-5" />
            <span>{t("creditRates")}:</span>
          </div>
          <div className="flex flex-wrap gap-4">
            {creditRates.map((rate) => {
              const Icon = rate.type === 'call' ? Phone : rate.type === 'sms' ? MessageSquare : Zap
              return (
                <div key={rate.type} className="flex items-center gap-2 text-gray-700 bg-white px-3 py-1.5 rounded-lg border border-blue-100 shadow-sm transition-all hover:border-primary/30">
                  <Icon className="w-4 h-4 text-primary" />
                  <span className="text-sm">
                    <strong>{rate.credits}</strong> {t("credits")} = <strong>1</strong> {t(rate.type)} / {t(rate.unit)}
                  </span>
                </div>
              )
            })}
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {activeTopups.map(topup => (
          <TopupCard
            key={topup._id}
            topup={topup}
            onPurchase={() => handlePurchase(topup)}
            isPurchasing={purchaseTopupMutation.isPending}
            purchasingTopupId={purchasingTopupId}
          />
        ))}
      </div>

      <StripePaymentModal
        isOpen={isPaymentModalOpen}
        onClose={handleCloseModal}
        clientSecret={clientSecret}
        topupName={selectedTopup?.name}
        amount={selectedTopup?.amountPaid}
        credits={selectedTopup?.credits}
        onPaymentSuccess={handlePaymentSuccess}
      />
    </>
  )
}
