import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import config from "@/config"
import { formatCurrency } from "@/utils/formatCurrency"
import { PackagePlus, DollarSign, Tag } from "lucide-react"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { PHASE_CONFIG } from "@/utils/lifecyclePhases"

interface PhaseBreakdown {
  phase: string
  products: number
  units: number
  cost: number
  percentage: number
}

interface ReplenishmentMetricsData {
  productsToReplenish: number
  unitsToReplenish: number
  replenishmentCost: number
  replenishmentRetail: number
  phaseBreakdown?: PhaseBreakdown[]
  topVariants: {
    id: number
    title: string
    currentStock: number
    replenishQty: number
    replenishCost: number
    replenishRetail: number
    status: string
    planningPeriod: string
  }[]
}

function MetricSkeleton() {
  return <div className="h-7 w-20 animate-pulse rounded bg-muted" />;
}

export function ReplenishmentMetrics() {
  const { data, isError, isLoading } = useQuery<ReplenishmentMetricsData>({
    queryKey: ["replenishment-metrics"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/replenishment/metrics`)
      if (!response.ok) throw new Error('Failed to fetch replenishment metrics');
      return response.json();
    },
  })

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Replenishment</CardTitle>
      </CardHeader>
      <CardContent>
        {isError ? (
          <p className="text-sm text-destructive">Failed to load replenishment metrics</p>
        ) : (
          <div className="flex flex-col gap-4">
            <div className="flex items-baseline justify-between">
              <div className="flex items-center gap-2">
                <PackagePlus className="h-4 w-4 text-muted-foreground" />
                <p className="text-sm font-medium text-muted-foreground">Units to Replenish</p>
              </div>
              {isLoading || !data ? <MetricSkeleton /> : (
                <p className="text-lg font-bold">{data.unitsToReplenish.toLocaleString()}</p>
              )}
            </div>
            <div className="flex items-baseline justify-between">
              <div className="flex items-center gap-2">
                <DollarSign className="h-4 w-4 text-muted-foreground" />
                <p className="text-sm font-medium text-muted-foreground">Replenishment Cost</p>
              </div>
              {isLoading || !data ? <MetricSkeleton /> : (
                <p className="text-lg font-bold">{formatCurrency(data.replenishmentCost)}</p>
              )}
            </div>
            <div className="flex items-baseline justify-between">
              <div className="flex items-center gap-2">
                <Tag className="h-4 w-4 text-muted-foreground" />
                <p className="text-sm font-medium text-muted-foreground">Replenishment Retail</p>
              </div>
              {isLoading || !data ? <MetricSkeleton /> : (
                <p className="text-lg font-bold">{formatCurrency(data.replenishmentRetail)}</p>
              )}
            </div>
            {data?.phaseBreakdown && data.phaseBreakdown.length > 0 && (
              <div className="mt-1 space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">Replenishment Cost By Lifecycle Phase</p>
                <TooltipProvider delayDuration={0}>
                  <div className="flex h-2.5 w-full overflow-hidden rounded-full">
                    {data.phaseBreakdown.map((p) => {
                      const cfg = PHASE_CONFIG[p.phase] || { label: p.phase, color: "#94A3B8" }
                      return (
                        <Tooltip key={p.phase}>
                          <TooltipTrigger asChild>
                            <div
                              className="h-full transition-all"
                              style={{
                                width: `${p.percentage}%`,
                                backgroundColor: cfg.color,
                                minWidth: p.percentage > 0 ? 3 : 0,
                              }}
                            />
                          </TooltipTrigger>
                          <TooltipContent side="bottom" className="text-xs">
                            <div className="flex items-center gap-1.5 font-medium">
                              <div className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: cfg.color }} />
                              {cfg.label}
                              <span className="font-normal opacity-70">{p.percentage}%</span>
                            </div>
                            <div className="mt-0.5 font-semibold">{formatCurrency(p.cost)}</div>
                            <div className="opacity-70">{p.products} products · {p.units} units</div>
                          </TooltipContent>
                        </Tooltip>
                      )
                    })}
                  </div>
                </TooltipProvider>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </>
  )
}
