"use client"

import React, { useMemo } from "react"
import { Zap, HelpCircle } from "lucide-react"
import { Progress } from "@/components/ui/progress"
import { format } from "date-fns"
import {
  formatCredits,
  calculateCreditsPercentage,
  getProgressBarClassName,
  roundCredits,
} from "@/lib/utils"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"

interface OptimizationUsageCardProps {
  optimizationsUsed: number
  optimizationsLimit: number
  currentPeriodEnd?: Date | null
  planType?: string
}

export const OptimizationUsageCard: React.FC<OptimizationUsageCardProps> = ({
  optimizationsUsed,
  optimizationsLimit,
  currentPeriodEnd,
  planType,
}) => {
  const percentage = useMemo(() => {
    return calculateCreditsPercentage(optimizationsUsed, optimizationsLimit)
  }, [optimizationsUsed, optimizationsLimit])

  const remaining = useMemo(() => {
    const roundedUsed = roundCredits(optimizationsUsed)
    const roundedLimit = roundCredits(optimizationsLimit)
    return Math.max(0, roundedLimit - roundedUsed)
  }, [optimizationsUsed, optimizationsLimit])

  const progressBarClassName = useMemo(() => {
    return getProgressBarClassName(percentage)
  }, [percentage])

  const formattedUsed = useMemo(() => {
    return formatCredits(optimizationsUsed)
  }, [optimizationsUsed])

  const formattedLimit = useMemo(() => {
    return formatCredits(optimizationsLimit)
  }, [optimizationsLimit])

  const formattedRemaining = useMemo(() => {
    return new Intl.NumberFormat("en-US").format(remaining)
  }, [remaining])

  const periodEndText = useMemo(() => {
    if (!currentPeriodEnd) return null
    try {
      return format(new Date(currentPeriodEnd), "MMM d, yyyy")
    } catch {
      return null
    }
  }, [currentPeriodEnd])

  const isMobile = typeof window !== "undefined" && window.innerWidth < 640

  return (
    <div className="bg-card rounded-xl border border-border p-4 hover:shadow-md transition-all duration-300 hover:border-primary/20 group h-full">
      <div className="flex items-start justify-between mb-4">
        <div className="flex-1">
          <div className="flex items-center gap-1.5 mb-1">
            <p className="text-muted-foreground text-xs sm:text-sm font-medium">
              Optimization Attempts Usage
            </p>
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    className="inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors"
                    aria-label="Optimization attempts calculation info"
                  >
                    <HelpCircle size={14} className="shrink-0" />
                  </button>
                </TooltipTrigger>
                <TooltipContent className="max-w-xs">
                  <p className="text-xs">
                    Confirmed performance gains use 1 attempt.
                    <br />
                    Search runs with no gains use just 0.5 attempt.
                    <br />
                    <br />
                    Your optimization attempts reset at the start of each billing cycle.
                  </p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>
          <div className="flex items-end gap-1 sm:gap-2 mt-1">
            <h3 className="text-xl sm:text-3xl font-bold text-foreground">{formattedUsed}</h3>
            <span className="text-muted-foreground text-sm sm:text-base mb-0.5 sm:mb-1">/</span>
            <span className="text-muted-foreground text-sm sm:text-base mb-0.5 sm:mb-1">
              {formattedLimit}
            </span>
          </div>
          <p className="text-xs sm:text-sm text-muted-foreground mt-1">
            {formattedRemaining} remaining
          </p>
        </div>
        <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl bg-gradient-to-br from-blue-500/20 to-blue-600/20 flex items-center justify-center text-blue-500">
          <Zap size={isMobile ? 16 : 20} />
        </div>
      </div>

      <div className="mt-4 space-y-2">
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <span>{percentage}% used</span>
          {planType && (
            <span className="capitalize text-xs px-2 py-0.5 rounded-md bg-muted">
              {planType} plan
            </span>
          )}
        </div>
        <div className="relative">
          <Progress value={percentage} className={`h-3 ${progressBarClassName}`} />
        </div>
        {periodEndText && (
          <p className="text-xs text-muted-foreground italic">Resets on {periodEndText}</p>
        )}
      </div>
    </div>
  )
}
