"use client"
import { useEffect, useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from "@/components/ui/card"
import {
  upgradeSubscription,
  cancelSubscription,
  getSubscription,
  reactivateSubscription,
} from "./actions"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useSearchParams, useRouter } from "next/navigation"
import { OptimizationUsageCard } from "@/components/dashboard/OptimizationUsageCard"

// @ts-expect-error - ToDo fix the type error
export function BillingView({ userId, subscription: initialSubscription, plans }) {
  const [subscription, setSubscription] = useState(initialSubscription)
  const [isLoading, setIsLoading] = useState(false)
  const [billingPeriod, setBillingPeriod] = useState<"monthly" | "yearly">("monthly")
  const searchParams = useSearchParams()
  const router = useRouter()
  const success = searchParams.get("success")

  // Fetch updated subscription data when success=true in URL
  useEffect(() => {
    if (success === "true") {
      setIsLoading(true)

      // Remove the success parameter from URL
      router.replace("/app/billing")

      // Fetch latest subscription data
      getSubscription(userId)
        .then(latestSubscription => {
          if (latestSubscription) {
            setSubscription(latestSubscription)
          }
        })
        .catch(err => console.error("Error fetching updated subscription:", err))
        .finally(() => setIsLoading(false))
    }
  }, [success, userId, router])

  const handleReactivate = async () => {
    setIsLoading(true)
    try {
      const result = await reactivateSubscription(userId)
      if (result.success) {
        // Fetch the updated subscription
        const updatedSubscription = await getSubscription(userId)
        if (updatedSubscription) {
          setSubscription(updatedSubscription)
        }
      } else {
        console.error("Failed to reactivate:", result.error)
      }
    } catch (error) {
      console.error("Error reactivating subscription:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleUpgrade = async () => {
    setIsLoading(true)
    try {
      // Pass the selected period
      const url = await upgradeSubscription(userId, billingPeriod)
      if (url) window.location.href = url
    } catch (error) {
      console.error("Error creating checkout:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleCancel = async () => {
    setIsLoading(true)
    try {
      await cancelSubscription(userId)
      // Fetch updated subscription data after cancellation
      const updatedSubscription = await getSubscription(userId)
      if (updatedSubscription) {
        setSubscription(updatedSubscription)
      }
      // Refresh page to show updated status
      // window.location.reload()
    } catch (error) {
      console.error("Error canceling subscription:", error)
    } finally {
      setIsLoading(false)
    }
  }

  // Calculate time remaining on cancelled subscription
  const daysRemaining = subscription.current_period_end
    ? Math.ceil(
        (new Date(subscription.current_period_end).getTime() - new Date().getTime()) /
          (1000 * 60 * 60 * 24),
      )
    : 0
  // Format cancellation date if available
  const cancellationDate = subscription.cancellation_request_date
    ? new Date(subscription.cancellation_request_date).toLocaleDateString("en-US", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      })
    : null

  const currentBillingPeriod =
    subscription.subscription_status === "active"
      ? subscription.stripe_subscription_id?.includes("year")
        ? "yearly"
        : "monthly"
      : null

  const proPlan = plans.PRO
  const formatPrice = (amount: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 0,
    }).format(amount / 100)
  }
  const handlePeriodChange = (value: string) => {
    if (value === "monthly" || value === "yearly") {
      setBillingPeriod(value)
    }
  }
  // Calculate yearly savings
  const monthlyCost = proPlan.monthlyPrice
  const yearlyCost = proPlan.yearlyPrice
  const monthlyCostPerYear = monthlyCost * 12
  const yearlySavings = monthlyCostPerYear - yearlyCost

  return (
    <div className="max-w-2xl p-6 space-y-6">
      <h1 className="text-2xl font-bold">Billing & Subscription</h1>

      {/* Optimization Usage Card */}
      <OptimizationUsageCard
        optimizationsUsed={subscription.optimizations_used || 0}
        optimizationsLimit={subscription.optimizations_limit || 0}
        currentPeriodEnd={subscription.current_period_end}
        planType={subscription.plan_type}
      />

      <Card>
        <CardHeader>
          <CardTitle>
            Current Plan:{" "}
            {subscription.plan_type.charAt(0).toUpperCase() + subscription.plan_type.slice(1)}
            {currentBillingPeriod && (
              <span className="ml-2 text-sm text-muted-foreground">({currentBillingPeriod})</span>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Display cancellation notice if applicable */}
          {subscription.cancel_at_period_end && (
            <div className="p-4 bg-yellow-50 rounded-md border border-yellow-200">
              <p className="font-medium">Your subscription has been cancelled</p>
              <p className="text-sm text-gray-500">
                You&apos;ll continue to have Pro access until{" "}
                {new Date(subscription.current_period_end).toLocaleDateString("en-US", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                })}
                {daysRemaining > 0 && ` (${daysRemaining} days remaining)`}
              </p>
              {cancellationDate && (
                <p className="text-xs text-gray-400 mt-1">Cancelled on {cancellationDate}</p>
              )}
              <Button
                variant="outline"
                size="sm"
                className="mt-2"
                onClick={handleReactivate}
                disabled={isLoading}
              >
                {isLoading ? "Processing..." : "Reactivate Subscription"}
              </Button>
            </div>
          )}

          {subscription.current_period_end && (
            <div>
              <p className="text-sm text-gray-500">Next Billing Date</p>
              <p>
                {new Date(subscription.current_period_end).toLocaleDateString("en-US", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                })}
              </p>
            </div>
          )}
        </CardContent>

        <CardFooter>
          {subscription.plan_type === "free" && (
            <div className="space-y-4 w-full">
              <Tabs
                defaultValue={billingPeriod}
                onValueChange={handlePeriodChange}
                className="w-full"
              >
                <TabsList className="grid grid-cols-2 w-full">
                  <TabsTrigger value="monthly">Monthly</TabsTrigger>
                  <TabsTrigger value="yearly">
                    Yearly (Save {formatPrice(yearlySavings)})
                  </TabsTrigger>
                </TabsList>
              </Tabs>

              <div className="flex flex-col space-y-2">
                {billingPeriod === "monthly" ? (
                  <p className="text-lg font-medium">{formatPrice(proPlan.monthlyPrice)}/month</p>
                ) : (
                  <p className="text-lg font-medium">
                    {formatPrice(proPlan.yearlyPrice)}/year
                    <span className="text-sm text-green-600 ml-2">
                      Save {formatPrice(yearlySavings)}
                    </span>
                  </p>
                )}

                <Button onClick={handleUpgrade} disabled={isLoading} className="w-full">
                  {isLoading ? "Loading..." : "Upgrade to Pro"}
                </Button>
              </div>
            </div>
          )}
          {subscription.plan_type === "pro" && (
            <Button variant="outline" disabled={isLoading} onClick={handleCancel}>
              Cancel Subscription
            </Button>
          )}
        </CardFooter>
      </Card>
    </div>
  )
}
