"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Check, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { BillingMethodSelector } from "./billing-method-selector"

interface SubscriptionPlan {
  id: string
  name: string
  description: string | null
  price: string
  interval: string
  trialDuration: number | null
  features: string[]
  isActive: boolean
  popular?: boolean
}

interface BillingMethod {
  id: string
  cardType: string
  last4: string
  expMonth: string
  expYear: string
  isDefault: boolean
}

export function PlanSelection() {
  const router = useRouter()
  const [plans, setPlans] = useState<SubscriptionPlan[]>([])
  const [billingMethods, setBillingMethods] = useState<BillingMethod[]>([])
  const [selectedPlan, setSelectedPlan] = useState<SubscriptionPlan | null>(null)
  const [selectedBillingMethod, setSelectedBillingMethod] = useState<string | null>(null)
  const [showBillingMethods, setShowBillingMethods] = useState(false)
  const [loading, setLoading] = useState(true)
  const [subscribing, setSubscribing] = useState(false)
  const [requireBillingMethod, setRequireBillingMethod] = useState(false)

  useEffect(() => {
    fetchPlansAndSettings()
  }, [])

  async function fetchPlansAndSettings() {
    try {
      // Fetch plans
      const plansRes = await fetch("/api/subscription/plans")
      const plansData = await plansRes.json()

      // Fetch app setting for billing method requirement
      const settingsRes = await fetch("/api/settings/subscription.require_billing_method")
      const settingsData = await settingsRes.json()

      setPlans(plansData.plans || [])
      setRequireBillingMethod(settingsData.value || false)
    } catch (error) {
      toast.error("Error", { description: "Failed to load subscription plans" })
    } finally {
      setLoading(false)
    }
  }

  async function fetchBillingMethods() {
    try {
      const res = await fetch("/api/billing-methods")
      const data = await res.json()
      setBillingMethods(data.billingMethods || [])

      // Auto-select default billing method
      const defaultMethod = data.billingMethods?.find((m: BillingMethod) => m.isDefault)
      if (defaultMethod) {
        setSelectedBillingMethod(defaultMethod.id)
      }
    } catch (error) {
      toast.error("Error", { description: "Failed to load billing methods" })
    }
  }

  function handlePlanSelect(plan: SubscriptionPlan) {
    setSelectedPlan(plan)

    // Check if we need to show billing methods
    const isFree = Number.parseFloat(plan.price) === 0
    const needsBilling = !isFree || requireBillingMethod

    if (needsBilling) {
      setShowBillingMethods(true)
      fetchBillingMethods()
    } else {
      setShowBillingMethods(false)
    }
  }

  async function handleSubscribe() {
    if (!selectedPlan) return

    const isFree = Number.parseFloat(selectedPlan.price) === 0
    const needsBilling = !isFree || requireBillingMethod

    // Validate billing method selection if required
    if (needsBilling && !selectedBillingMethod) {
      toast.error("Billing method required", { description: "Please select or add a billing method to continue" })
      return
    }

    setSubscribing(true)

    try {
      const res = await fetch("/api/subscription/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          planId: selectedPlan.id,
          billingMethodId: selectedBillingMethod,
        }),
      })

      const data = await res.json()

      if (!res.ok) {
        throw new Error(data.error || "Failed to subscribe")
      }

      toast("Success!", { description: 'You have subscribed' })

      // Redirect to dashboard
      router.push("/dashboard")
    } catch (error: any) {
      toast.error("Subscription failed", { description: error.message })
    } finally {
      setSubscribing(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-100">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <div className="w-full max-w-6xl mx-auto space-y-8">
      {/* Header */}
      <div className="text-center space-y-2">
        <img src="/images/logo-icon.svg" alt="Kokotrack" className="h-12 w-12 mx-auto mb-4" />
        <h1 className="text-3xl font-bold">Choose Your Plan</h1>
        <p className="text-muted-foreground">Select the perfect plan for your trading journey</p>
      </div>

      {/* Plans Grid */}
      <div className="grid gap-6 md:grid-cols-3">
        {plans.map((plan) => {
          const isFree = Number.parseFloat(plan.price) === 0
          const isSelected = selectedPlan?.id === plan.id

          return (
            <Card
              key={plan.id}
              className={`relative cursor-pointer transition-all ${
                isSelected ? "border-primary shadow-lg ring-2 ring-primary" : "hover:border-primary/50"
              } ${plan.popular ? "border-primary" : ""}`}
              onClick={() => handlePlanSelect(plan)}
            >
              {plan.popular && (
                <Badge className="absolute -top-3 left-1/2 transform -translate-x-1/2">Most Popular</Badge>
              )}

              <CardHeader className="text-center">
                <CardTitle className="text-xl">{plan.name}</CardTitle>
                {plan.description && <CardDescription>{plan.description}</CardDescription>}
                <div className="mt-4">
                  <span className="text-4xl font-bold">{isFree ? "Free" : `$${plan.price}`}</span>
                  {!isFree && <span className="text-muted-foreground text-sm">/{plan.interval}</span>}
                </div>
                {plan.trialDuration && (
                  <Badge variant="outline" className="mt-2">
                    {plan.trialDuration} days free trial
                  </Badge>
                )}
              </CardHeader>

              <CardContent>
                <ul className="space-y-3 mb-6">
                  {plan.features.map((feature, index) => (
                    <li key={index} className="flex items-start gap-2 text-sm">
                      <Check className="h-4 w-4 text-success mt-0.5 shrink-0" />
                      <span>{feature}</span>
                    </li>
                  ))}
                </ul>
              </CardContent>
            </Card>
          )
        })}
      </div>

      {/* Billing Methods Section */}
      {showBillingMethods && selectedPlan && (
        <Card>
          <CardHeader>
            <CardTitle>Select Payment Method</CardTitle>
            <CardDescription>Choose a billing method for your {selectedPlan.name} subscription</CardDescription>
          </CardHeader>
          <CardContent>
            <BillingMethodSelector
              billingMethods={billingMethods}
              selectedId={selectedBillingMethod}
              onSelect={setSelectedBillingMethod}
              onAdd={() => {
                // Redirect to add billing method page
                router.push("/billing/add")
              }}
            />
          </CardContent>
        </Card>
      )}

      {/* Subscribe Button */}
      {selectedPlan && (
        <div className="flex justify-center">
          <Button
            size="lg"
            className="w-full max-w-md"
            onClick={handleSubscribe}
            disabled={subscribing || (showBillingMethods && !selectedBillingMethod)}
          >
            {subscribing ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Processing...
              </>
            ) : (
              <>
                {selectedPlan.trialDuration
                  ? `Start ${selectedPlan.trialDuration}-Day Free Trial`
                  : `Subscribe to ${selectedPlan.name}`}
              </>
            )}
          </Button>
        </div>
      )}
    </div>
  )
}
