'use client'

import { useState, useEffect } from 'react'
import { useAuthUser } from '@/hooks/useAuthUser'
import { useTranslations } from 'next-intl'
import { Crown, Star, AlertTriangle, CheckCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getPlanTheme } from '@/lib/subscription-utils'

interface SubscriptionData {
  subscription: {
    isActive: boolean
    planId: string
    stripeSubscriptionId?: string
    currentPeriodStart?: Date
    currentPeriodEnd?: Date
    cancelAtPeriodEnd?: boolean
    status?: string
  }
  permissions: {
    maxVersionLimit: number
    promptLimit: number
    features: string[]
    canCreatePrompt: boolean
    canCreateVersion: boolean
  }
  plan?: {
    id: string
    displayName: string
    price: number
  }
}

interface SubscriptionStatusProps {
  className?: string
  showDetails?: boolean
}

export function SubscriptionStatus({ className, showDetails = true }: SubscriptionStatusProps) {
  const { userData } = useAuthUser()
  const t = useTranslations('subscription')
  const [subscriptionData, setSubscriptionData] = useState<SubscriptionData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchSubscriptionData = async () => {
      try {
        const response = await fetch('/api/subscription/manage')
        if (response.ok) {
          const data = await response.json()
          setSubscriptionData(data)
        }
      } catch (error) {
        console.error('Failed to fetch subscription data:', error)
      } finally {
        setLoading(false)
      }
    }

    if (userData) {
      fetchSubscriptionData()
    } else {
      setLoading(false)
    }
  }, [userData])

  if (loading) {
    return (
      <div className={cn("animate-pulse", className)}>
        <div className="h-16 bg-muted rounded-lg"></div>
      </div>
    )
  }

  const planData = subscriptionData?.plan
  const isPro = planData ? planData.price > 19 : false
  const theme = getPlanTheme(planData)
  const subscription = subscriptionData?.subscription
  const permissions = subscriptionData?.permissions

  return (
    <div className={cn("bg-card rounded-lg border border-border overflow-hidden", className)}>
      <div className={`p-4 border-b border-border ${theme.gradient}`}>
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className={`p-2 rounded-full ${theme.iconGradient}`}>
              {isPro ? (
                <Crown className="w-5 h-5 text-white" />
              ) : (
                <Star className="w-5 h-5 text-white" />
              )}
            </div>
            <div>
              <h3 className="font-semibold text-foreground">
                {t('currentPlan')}
              </h3>
              <p className={`text-sm font-medium ${theme.textColor}`}>
                {isPro ? t('proPlan') : t('freePlan')}
              </p>
            </div>
          </div>

          {/* Status indicator */}
          <div className="flex items-center space-x-2">
            {subscription?.cancelAtPeriodEnd ? (
              <div className="flex items-center text-orange-600 dark:text-orange-400">
                <AlertTriangle className="w-4 h-4 mr-1" />
                <span className="text-xs font-medium">Canceling</span>
              </div>
            ) : isPro ? (
              <div className="flex items-center text-green-600 dark:text-green-400">
                <CheckCircle className="w-4 h-4 mr-1" />
                <span className="text-xs font-medium">Active</span>
              </div>
            ) : null}
          </div>
        </div>
      </div>

      {showDetails && (
        <div className="p-4">
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground">Prompts:</span>
              <span className="ml-2 font-medium">
                {permissions?.promptLimit || (isPro ? '5000' : '500')}
              </span>
            </div>
            <div>
              <span className="text-muted-foreground">Versions:</span>
              <span className="ml-2 font-medium">
                {permissions?.maxVersionLimit || (isPro ? '10' : '3')} per prompt
              </span>
            </div>
          </div>

          {subscription?.currentPeriodEnd && (
            <div className="mt-4 pt-4 border-t border-border">
              <div className="text-sm">
                <span className="text-muted-foreground">{t('nextBilling')}:</span>
                <span className="ml-2 font-medium">
                  {new Date(subscription.currentPeriodEnd).toLocaleDateString()}
                </span>
              </div>
              {subscription.cancelAtPeriodEnd && (
                <div className="mt-2 text-xs text-orange-600 dark:text-orange-400">
                  Subscription will end on the next billing date
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
