import * as React from 'react';
import { apiFetch } from '@/utils/api';
import { useQuery } from "@tanstack/react-query";
import { Drawer as VaulDrawer } from "vaul";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import { ProductMetric } from "@/types/products";
import {
  formatCurrency,
  formatNumber,
  formatPercentage,
  formatDays,
  formatDate,
  formatBoolean
} from "@/utils/productUtils";
import { StatusBadge } from "@/components/products/StatusBadge";
import { transformMetricsRow } from "@/utils/transformUtils";
import { cn } from "@/lib/utils";
import config from "@/config";
import { ResponsiveContainer, LineChart, Line, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid, Legend } from "recharts";
import { Badge } from "@/components/ui/badge";
import { format } from "date-fns";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table";

// Interfaces for POs and time series data
interface ProductPurchaseOrder {
  poId: string;
  date: string;
  expectedDate: string;
  receivedDate: string | null;
  ordered: number;
  received: number;
  status: string;
  costPrice: number;
  notes: string | null;
  leadTimeDays: number | null;
}

interface ProductTimeSeries {
  monthlySales: {
    month: string;
    sales: number;
    revenue: number;
  }[];
  recentPurchases: ProductPurchaseOrder[];
}

interface ProductForecast {
  phase: string | null;
  method: string | null;
  forecast: {
    date: string;
    units: number;
    revenue: number;
    confidenceLower: number;
    confidenceUpper: number;
  }[];
}

const PHASE_LABELS: Record<string, string> = {
  preorder: "Pre-order",
  launch: "Launch",
  decay: "Active Decay",
  mature: "Evergreen",
  dormant: "Dormant",
};

interface ProductDetailProps {
  productId: number | null;
  onClose: () => void;
}

export function ProductDetail({ productId, onClose }: ProductDetailProps) {
  const { data: product, isLoading: isLoadingProduct, error } = useQuery<ProductMetric, Error>({
    queryKey: ["productMetricDetail", productId],
    queryFn: async () => {
      if (!productId) throw new Error("Product ID is required");
      const response = await apiFetch(`${config.apiUrl}/metrics/${productId}`, {credentials: 'include'});
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`Failed to fetch product details (${response.status}): ${errorData.error || 'Server error'}`);
      }
      const rawData = await response.json();
      return transformMetricsRow(rawData) as ProductMetric;
    },
    enabled: !!productId, // Only run query when productId is truthy
  });

  // Fetch time series data and purchase orders history
  const { data: timeSeriesData, isLoading: isLoadingTimeSeries } = useQuery<ProductTimeSeries, Error>({
    queryKey: ["productTimeSeries", productId],
    queryFn: async () => {
      if (!productId) throw new Error("Product ID is required");
      const response = await apiFetch(`${config.apiUrl}/products/${productId}/time-series`, {credentials: 'include'});
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`Failed to fetch time series data (${response.status}): ${errorData.error || 'Server error'}`);
      }
      const data = await response.json();

      // Map backend field names (units_sold) to frontend chart keys (sales)
      // Reverse from DESC to ASC so the chart shows oldest-to-newest (left-to-right)
      const formattedMonthlySales = [...(data.monthly_sales || [])].reverse().map((item: any) => ({
        month: item.month,
        sales: Number(item.units_sold || 0),
        revenue: Number(item.revenue || 0),
      }));

      // Transform snake_case PO fields to camelCase expected by ProductPurchaseOrder
      const formattedPurchases: ProductPurchaseOrder[] = (data.recent_purchases || []).map((po: any) => ({
        poId: po.po_id,
        date: po.date,
        expectedDate: po.expected_date,
        receivedDate: po.received_date,
        ordered: po.ordered,
        received: po.received,
        status: po.status,
        costPrice: po.cost_price,
        notes: po.notes,
        leadTimeDays: po.lead_time_days,
      }));

      return {
        monthlySales: formattedMonthlySales,
        recentPurchases: formattedPurchases,
      };
    },
    enabled: !!productId, // Only run query when productId is truthy
  });

  // Fetch product forecast data
  const { data: forecastData, isLoading: isLoadingForecast } = useQuery<ProductForecast, Error>({
    queryKey: ["productForecast", productId],
    queryFn: async () => {
      if (!productId) throw new Error("Product ID is required");
      const response = await apiFetch(`${config.apiUrl}/products/${productId}/forecast`, {credentials: 'include'});
      if (!response.ok) throw new Error("Failed to fetch forecast");
      return response.json();
    },
    enabled: !!productId,
  });

  // Get PO status display names (DB stores text statuses)
  const getPOStatusName = (status: string): string => {
    const statusMap: Record<string, string> = {
      canceled: 'Canceled',
      created: 'Created',
      ordered: 'Ordered',
      electronically_sent: 'Electronically Sent',
      receiving_started: 'Receiving Started',
      done: 'Completed',
    };
    return statusMap[status] || 'Unknown';
  };

  // Get status badge color class
  const getStatusBadgeClass = (status: string): string => {
    if (status === 'canceled') return "bg-destructive text-destructive-foreground";
    if (status === 'done') return "bg-green-600 text-white";
    if (status === 'receiving_started') return "bg-amber-500 text-black";
    return "bg-blue-600 text-white"; // created, ordered, electronically_sent
  };

  if (!productId) return null; // Don't render anything if no ID

  return (
    <VaulDrawer.Root open={!!productId} onOpenChange={(open) => !open && onClose()} direction="right">
      <VaulDrawer.Portal>
        <VaulDrawer.Overlay className="fixed inset-0 bg-black/40 z-40" />
        <VaulDrawer.Content className="fixed right-0 top-0 h-dvh w-[90%] max-w-[800px] bg-background p-0 shadow-lg flex flex-col z-50">
            {/* Header */}
            <div className="flex items-start justify-between p-4 border-b sticky top-0 bg-background z-10">
                <div className="flex items-center gap-4 overflow-hidden">
                    {isLoadingProduct ? (
                        <Skeleton className="h-16 w-16 rounded-lg" />
                    ) : product?.imageUrl ? (
                        <div className="h-16 w-16 rounded-lg border bg-white p-1 flex-shrink-0">
                            <img src={product.imageUrl} alt={product.title || 'Product'} className="h-full w-full object-contain" />
                        </div>
                    ) : (
                         <div className="h-16 w-16 rounded-lg border bg-muted flex items-center justify-center text-xs text-muted-foreground flex-shrink-0">No Image</div>
                    )}
                    <div className="flex-1 min-w-0">
                        <VaulDrawer.Title className="text-lg font-semibold truncate">
                            {isLoadingProduct ? <Skeleton className="h-6 w-3/4" /> : product?.title || 'Product Detail'}
                        </VaulDrawer.Title>
                        <VaulDrawer.Description className="text-sm text-muted-foreground">
                            {isLoadingProduct ? <Skeleton className="h-4 w-1/2 mt-1" /> : (
                                <>
                                    {product?.sku || ''}
                                    {product?.lastCalculated && (
                                        <span className="ml-2 text-xs text-muted-foreground/70">
                                            &middot; Updated {formatDate(product.lastCalculated)}
                                        </span>
                                    )}
                                </>
                            )}
                        </VaulDrawer.Description>
                         {/* Show Status Badge */}
                         {!isLoadingProduct && product && (
                            <div className="mt-1"><StatusBadge status={product.status as string} /></div>
                         )}
                    </div>
                </div>
                <Button variant="ghost" size="icon" onClick={onClose} className="ml-4 flex-shrink-0">
                    <X className="h-4 w-4" />
                </Button>
            </div>

             {/* Content Area */}
            <div className="flex-1 overflow-y-auto">
                {isLoadingProduct ? (
                    <div className="p-4 space-y-4">
                        <Skeleton className="h-8 w-1/2" />
                        <div className="grid grid-cols-2 gap-4">
                            <Skeleton className="h-32 w-full" />
                            <Skeleton className="h-32 w-full" />
                            <Skeleton className="h-24 w-full" />
                            <Skeleton className="h-24 w-full" />
                        </div>
                    </div>
                 ) : error ? (
                    <div className="p-4 text-center text-destructive">
                        Error loading product details: {error.message}
                    </div>
                 ) : product ? (
                    <Tabs defaultValue="overview" className="p-4">
                        <TabsList className="mb-4 grid w-full grid-cols-5 h-auto">
                            <TabsTrigger value="overview">Overview</TabsTrigger>
                            <TabsTrigger value="inventory">Inventory</TabsTrigger>
                            <TabsTrigger value="performance">Performance</TabsTrigger>
                            <TabsTrigger value="orders">Orders</TabsTrigger>
                            <TabsTrigger value="details">Details</TabsTrigger>
                        </TabsList>

                        <TabsContent value="overview" className="space-y-4">
                            <Card>
                                <CardHeader><CardTitle className="text-base">Key Info</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Brand" value={product.brand || 'N/A'} />
                                    <InfoItem label="Vendor" value={product.vendor || 'N/A'} />
                                    <InfoItem label="SKU" value={product.sku} />
                                    <InfoItem label="ABC Class" value={product.abcClass || 'N/A'} />
                                    <InfoItem label="Replenishable" value={formatBoolean(product.isReplenishable)} />
                                    <InfoItem label="Visible" value={formatBoolean(product.isVisible)} />
                                </CardContent>
                            </Card>
                             <Card>
                                <CardHeader><CardTitle className="text-base">Pricing & Cost</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Current Price" value={formatCurrency(product.currentPrice)} />
                                     <InfoItem label="Regular Price" value={formatCurrency(product.currentRegularPrice)} />
                                     <InfoItem label="Cost Price" value={formatCurrency(product.currentCostPrice)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Customer Engagement</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Rating" value={product.rating != null ? `${product.rating.toFixed(1)} / 5` : 'N/A'} />
                                    <InfoItem label="Reviews" value={formatNumber(product.reviews)} />
                                    <InfoItem label="Basket Adds" value={formatNumber(product.baskets)} />
                                    <InfoItem label="Stock Alerts" value={formatNumber(product.notifies)} />
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="inventory" className="space-y-4">
                            <Card>
                                <CardHeader><CardTitle className="text-base">Current Stock</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Shelf Count" value={formatNumber(product.currentStock)} isLarge={true} />
                                     <InfoItem label="Stock Cost Value" value={formatCurrency(product.currentStockCost)} />
                                     <InfoItem label="Stock Retail Value" value={formatCurrency(product.currentStockRetail)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Stock Position</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Status" value={<div className="scale-90 origin-left"><StatusBadge status={product.status as string} /></div>} />
                                     <InfoItem label="Stock Cover" value={formatDays(product.stockCoverInDays)} />
                                     <InfoItem label="Sells Out In" value={formatDays(product.sellsOutInDays)} />
                                     <InfoItem label="Overstock Units" value={formatNumber(product.overstockedUnits)} />
                                      <InfoItem label="Overstock Cost" value={formatCurrency(product.overstockedCost)} />
                                       <InfoItem label="Is Old Stock" value={formatBoolean(product.isOldStock)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">On Order</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Quantity" value={formatNumber(product.onOrderQty)} />
                                    <InfoItem label="Cost Value" value={formatCurrency(product.onOrderCost)} />
                                    <InfoItem label="Earliest Arrival" value={formatDate(product.earliestExpectedDate)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Service Level (30 Days)</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Fill Rate" value={formatPercentage(product.fillRate30d)} />
                                    <InfoItem label="Service Level" value={formatPercentage(product.serviceLevel30d)} />
                                    <InfoItem label="Stockout Incidents" value={formatNumber(product.stockoutIncidents30d)} />
                                    <InfoItem label="Lost Sales Incidents" value={formatNumber(product.lostSalesIncidents30d)} />
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="performance" className="space-y-4">
                            {/* Sales Performance Chart */}
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-base">Sales & Revenue Trend</CardTitle>
                                    <CardDescription>Monthly performance over time</CardDescription>
                                </CardHeader>
                                <CardContent className="h-[300px]">
                                    {isLoadingTimeSeries ? (
                                        <div className="w-full h-full flex items-center justify-center">
                                            <Skeleton className="h-[250px] w-full" />
                                        </div>
                                    ) : timeSeriesData && timeSeriesData.monthlySales && timeSeriesData.monthlySales.length > 0 ? (
                                        <ResponsiveContainer width="100%" height="100%">
                                            <LineChart
                                                data={timeSeriesData.monthlySales}
                                                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                                            >
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="month" />
                                                <YAxis yAxisId="left" />
                                                <YAxis yAxisId="right" orientation="right" />
                                                <Tooltip
                                                    formatter={(value: number, name: string) => {
                                                        if (name === 'Revenue') {
                                                            return [formatCurrency(value), name];
                                                        }
                                                        return [value, name];
                                                    }}
                                                />
                                                <Legend />
                                                <Line
                                                    yAxisId="left"
                                                    type="monotone"
                                                    dataKey="sales"
                                                    name="Units Sold"
                                                    stroke="#8884d8"
                                                    activeDot={{ r: 8 }}
                                                />
                                                <Line
                                                    yAxisId="right"
                                                    type="monotone"
                                                    dataKey="revenue"
                                                    name="Revenue"
                                                    stroke="#82ca9d"
                                                />
                                            </LineChart>
                                        </ResponsiveContainer>
                                    ) : (
                                        <div className="w-full h-full flex flex-col items-center justify-center text-muted-foreground">
                                            <p>No sales data available for this product.</p>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                            
                            {/* Forecast Chart */}
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-base">90-Day Forecast</CardTitle>
                                    <CardDescription>
                                        {forecastData?.phase
                                            ? `${PHASE_LABELS[forecastData.phase] || forecastData.phase} phase \u00b7 ${forecastData.method || 'unknown'} method`
                                            : 'Lifecycle-aware demand forecast'}
                                    </CardDescription>
                                </CardHeader>
                                <CardContent className="h-[300px]">
                                    {isLoadingForecast ? (
                                        <div className="w-full h-full flex items-center justify-center">
                                            <Skeleton className="h-[250px] w-full" />
                                        </div>
                                    ) : forecastData && forecastData.forecast.length > 0 ? (
                                        <ResponsiveContainer width="100%" height="100%">
                                            <AreaChart
                                                data={forecastData.forecast}
                                                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                                            >
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis
                                                    dataKey="date"
                                                    tickFormatter={(d) => format(new Date(d + 'T00:00:00'), 'MMM d')}
                                                    interval="preserveStartEnd"
                                                    tick={{ fontSize: 11 }}
                                                />
                                                <YAxis yAxisId="left" tick={{ fontSize: 11 }} />
                                                <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 11 }} />
                                                <Tooltip
                                                    labelFormatter={(d) => format(new Date(d + 'T00:00:00'), 'MMM d, yyyy')}
                                                    formatter={(value: number, name: string) => {
                                                        if (name === 'Revenue') return [formatCurrency(value), name];
                                                        return [value.toFixed(1), name];
                                                    }}
                                                />
                                                <Legend />
                                                <Area
                                                    yAxisId="left"
                                                    type="monotone"
                                                    dataKey="units"
                                                    name="Units"
                                                    stroke="#8884d8"
                                                    fill="#8884d8"
                                                    fillOpacity={0.15}
                                                />
                                                <Area
                                                    yAxisId="right"
                                                    type="monotone"
                                                    dataKey="revenue"
                                                    name="Revenue"
                                                    stroke="#82ca9d"
                                                    fill="#82ca9d"
                                                    fillOpacity={0.15}
                                                />
                                            </AreaChart>
                                        </ResponsiveContainer>
                                    ) : (
                                        <div className="w-full h-full flex flex-col items-center justify-center text-muted-foreground">
                                            <p>No forecast data available for this product.</p>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader><CardTitle className="text-base">Sales Performance (30 Days)</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Units Sold" value={formatNumber(product.sales30d)} />
                                    <InfoItem label="Revenue" value={formatCurrency(product.revenue30d)} />
                                    <InfoItem label="Profit" value={formatCurrency(product.profit30d)} />
                                    <InfoItem label="COGS" value={formatCurrency(product.cogs30d)} />
                                    <InfoItem label="Margin %" value={formatPercentage(product.margin30d)} />
                                    <InfoItem label="Avg Selling Price" value={formatCurrency(product.asp30d)} />
                                    <InfoItem label="Daily Velocity" value={formatNumber(product.salesVelocityDaily, 2)} />
                                </CardContent>
                            </Card>
                            
                            <Card>
                                <CardHeader><CardTitle className="text-base">Growth Analysis</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Sales Growth (30d vs Prev)" value={formatPercentage(product.salesGrowth30dVsPrev)} />
                                    <InfoItem label="Revenue Growth (30d vs Prev)" value={formatPercentage(product.revenueGrowth30dVsPrev)} />
                                    <InfoItem label="Sales Growth YoY" value={formatPercentage(product.salesGrowthYoy)} />
                                    <InfoItem label="Revenue Growth YoY" value={formatPercentage(product.revenueGrowthYoy)} />
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader><CardTitle className="text-base">Inventory Performance (30 Days)</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Stock Turn" value={formatNumber(product.stockturn30d, 2)} />
                                    <InfoItem label="Sell Through %" value={formatPercentage(product.sellThrough30d)} />
                                    <InfoItem label="GMROI" value={formatNumber(product.gmroi30d, 2)} />
                                     <InfoItem label="Stockout Days" value={formatDays(product.stockoutDays30d)} />
                                     <InfoItem label="Avg Stock Units" value={formatNumber(product.avgStockUnits30d, 1)} />
                                     <InfoItem label="Avg Stock Cost" value={formatCurrency(product.avgStockCost30d)} />
                                </CardContent>
                            </Card>
                             <Card>
                                <CardHeader><CardTitle className="text-base">Historical Performance</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Sales (365d)" value={formatNumber(product.sales365d)} />
                                     <InfoItem label="Revenue (365d)" value={formatCurrency(product.revenue365d)} />
                                      <InfoItem label="Avg Lead Time" value={formatDays(product.avgLeadTimeDays, 1)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Additional Metrics</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Returns (Units)" value={formatNumber(product.returnsUnits30d)} />
                                    <InfoItem label="Returns (Revenue)" value={formatCurrency(product.returnsRevenue30d)} />
                                    <InfoItem label="Return Rate" value={formatPercentage(product.returnRate30d)} />
                                    <InfoItem label="Discounts" value={formatCurrency(product.discounts30d)} />
                                    <InfoItem label="Discount Rate" value={formatPercentage(product.discountRate30d)} />
                                    <InfoItem label="Markdown" value={formatCurrency(product.markdown30d)} />
                                    <InfoItem label="Markdown Rate" value={formatPercentage(product.markdownRate30d)} />
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="orders" className="space-y-4">
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-base">Purchase Orders & Receivings</CardTitle>
                                    <CardDescription>Recent purchase orders for this product</CardDescription>
                                </CardHeader>
                                <CardContent>
                                    {isLoadingTimeSeries ? (
                                        <div className="space-y-2">
                                            <Skeleton className="h-8 w-full" />
                                            <Skeleton className="h-8 w-full" />
                                            <Skeleton className="h-8 w-full" />
                                        </div>
                                    ) : timeSeriesData?.recentPurchases && timeSeriesData.recentPurchases.length > 0 ? (
                                        <div className="rounded-md border overflow-hidden">
                                            <Table>
                                                <TableHeader>
                                                    <TableRow>
                                                        <TableHead>PO #</TableHead>
                                                        <TableHead>Date</TableHead>
                                                        <TableHead>Status</TableHead>
                                                        <TableHead className="text-right">Qty</TableHead>
                                                        <TableHead className="text-right">Received</TableHead>
                                                        <TableHead className="text-right">Cost</TableHead>
                                                    </TableRow>
                                                </TableHeader>
                                                <TableBody>
                                                    {timeSeriesData.recentPurchases.map((po) => (
                                                        <TableRow key={po.poId}>
                                                            <TableCell className="font-medium">{po.poId}</TableCell>
                                                            <TableCell>{po.date}</TableCell>
                                                            <TableCell>
                                                                <Badge className={getStatusBadgeClass(po.status)}>
                                                                    {getPOStatusName(po.status)}
                                                                </Badge>
                                                            </TableCell>
                                                            <TableCell className="text-right">{po.ordered}</TableCell>
                                                            <TableCell className="text-right">{po.received}</TableCell>
                                                            <TableCell className="text-right">{formatCurrency(po.costPrice)}</TableCell>
                                                        </TableRow>
                                                    ))}
                                                </TableBody>
                                            </Table>
                                        </div>
                                    ) : (
                                        <div className="text-center py-4 text-muted-foreground">
                                            <p>No purchase orders found for this product.</p>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                            
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-base">Order Summary</CardTitle>
                                </CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem 
                                        label="Total Ordered" 
                                        value={
                                            timeSeriesData?.recentPurchases ? 
                                            formatNumber(
                                                timeSeriesData.recentPurchases.reduce((acc, po) => acc + po.ordered, 0)
                                            ) : 'N/A'
                                        } 
                                    />
                                    <InfoItem 
                                        label="Total Received" 
                                        value={
                                            timeSeriesData?.recentPurchases ? 
                                            formatNumber(
                                                timeSeriesData.recentPurchases.reduce((acc, po) => acc + po.received, 0)
                                            ) : 'N/A'
                                        } 
                                    />
                                    <InfoItem
                                        label="Fulfillment Rate"
                                        value={
                                            timeSeriesData?.recentPurchases ?
                                            (() => {
                                                // Only include POs where receiving has started or completed for an accurate rate
                                                const receivingPOs = timeSeriesData.recentPurchases.filter(po => ['receiving_started', 'done'].includes(po.status));
                                                const totalOrdered = receivingPOs.reduce((acc, po) => acc + po.ordered, 0);
                                                const totalReceived = receivingPOs.reduce((acc, po) => acc + po.received, 0);
                                                return totalOrdered > 0 ? formatPercentage((totalReceived / totalOrdered) * 100) : 'N/A';
                                            })() : 'N/A'
                                        }
                                    />
                                    <InfoItem 
                                        label="Total PO Cost" 
                                        value={
                                            timeSeriesData?.recentPurchases ? 
                                            formatCurrency(
                                                timeSeriesData.recentPurchases.reduce((acc, po) => acc + (po.ordered * po.costPrice), 0)
                                            ) : 'N/A'
                                        } 
                                    />
                                    <InfoItem 
                                        label="Avg Lead Time" 
                                        value={
                                            timeSeriesData?.recentPurchases ? 
                                            (() => {
                                                const leadTimes = timeSeriesData.recentPurchases
                                                    .filter(po => po.leadTimeDays != null)
                                                    .map(po => po.leadTimeDays as number);
                                                const avgLeadTime = leadTimes.length > 0 
                                                    ? leadTimes.reduce((acc, lt) => acc + lt, 0) / leadTimes.length 
                                                    : null;
                                                return formatDays(avgLeadTime);
                                            })() : 'N/A'
                                        } 
                                    />
                                    <InfoItem 
                                        label="Active Orders" 
                                        value={
                                            timeSeriesData?.recentPurchases ? 
                                            formatNumber(
                                                timeSeriesData.recentPurchases.filter(
                                                    po => !['done', 'canceled'].includes(po.status)
                                                ).length
                                            ) : 'N/A'
                                        } 
                                    />
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="details" className="space-y-4">
                             <Card>
                                <CardHeader><CardTitle className="text-base">Dates</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Created" value={formatDate(product.dateCreated)} />
                                     <InfoItem label="First Sold" value={formatDate(product.dateFirstSold)} />
                                     <InfoItem label="Last Sold" value={formatDate(product.dateLastSold)} />
                                     <InfoItem label="First Received" value={formatDate(product.dateFirstReceived)} />
                                     <InfoItem label="Last Received" value={formatDate(product.dateLastReceived)} />
                                      <InfoItem label="Age" value={formatDays(product.ageDays)} />
                                      <InfoItem label="Replenish Date" value={formatDate(product.replenishDate)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Configuration</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                     <InfoItem label="Lead Time" value={formatDays(product.configLeadTime)} />
                                     <InfoItem label="Days of Stock" value={formatDays(product.configDaysOfStock)} />
                                     <InfoItem label="Safety Stock" value={formatNumber(product.configSafetyStock)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Forecasting</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Lifecycle Phase" value={forecastData?.phase ? (PHASE_LABELS[forecastData.phase] || forecastData.phase) : 'N/A'} />
                                    <InfoItem label="Forecast Method" value={forecastData?.method || 'N/A'} />
                                    <InfoItem label="Replenishment Units" value={formatNumber(product.replenishmentUnits)} />
                                    <InfoItem label="Replenishment Cost" value={formatCurrency(product.replenishmentCost)} />
                                    <InfoItem label="To Order Units" value={formatNumber(product.toOrderUnits)} />
                                    <InfoItem label="Forecast Lost Sales" value={formatNumber(product.forecastLostSalesUnits)} />
                                    <InfoItem label="Forecast Lost Revenue" value={formatCurrency(product.forecastLostRevenue)} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Demand & Seasonality</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Demand Pattern" value={product.demandPattern || 'N/A'} />
                                    <InfoItem label="Sales CV %" value={formatPercentage(product.salesCv30d)} />
                                    <InfoItem label="Sales Std Dev" value={formatNumber(product.salesStdDev30d, 2)} />
                                    <InfoItem label="Seasonality Index" value={formatNumber(product.seasonalityIndex, 2)} />
                                    <InfoItem label="Seasonal Pattern" value={product.seasonalPattern || 'N/A'} />
                                    <InfoItem label="Peak Season" value={product.peakSeason || 'N/A'} />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader><CardTitle className="text-base">Lifetime & First Period</CardTitle></CardHeader>
                                <CardContent className="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2 text-sm">
                                    <InfoItem label="Lifetime Sales" value={formatNumber(product.lifetimeSales)} />
                                    <InfoItem label="Lifetime Revenue" value={formatCurrency(product.lifetimeRevenue)} />
                                    <InfoItem label="Revenue Quality" value={product.lifetimeRevenueQuality || 'N/A'} />
                                    <InfoItem label="First 7d Sales" value={formatNumber(product.first7DaysSales)} />
                                    <InfoItem label="First 30d Sales" value={formatNumber(product.first30DaysSales)} />
                                    <InfoItem label="First 60d Sales" value={formatNumber(product.first60DaysSales)} />
                                    <InfoItem label="First 90d Sales" value={formatNumber(product.first90DaysSales)} />
                                </CardContent>
                            </Card>
                        </TabsContent>
                    </Tabs>
                 ) : null}
            </div>
        </VaulDrawer.Content>
      </VaulDrawer.Portal>
    </VaulDrawer.Root>
  );
}

// Helper component for consistent display in detail view
const InfoItem = ({ label, value, isLarge = false }: { label: string; value: React.ReactNode, isLarge?: boolean }) => (
    <div>
        <dt className="text-xs text-muted-foreground">{label}</dt>
        <dd className={cn("font-medium", isLarge ? "text-xl" : "text-sm")}>{value}</dd>
    </div>
);
