import * as React from 'react';
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, ProductStatus } from "@/types/products";
import { 
  getStatusBadge, 
  formatCurrency, 
  formatNumber, 
  formatPercentage, 
  formatDays, 
  formatDate, 
  formatBoolean
} from "@/utils/productUtils";
import { cn } from "@/lib/utils";
import config from "@/config";
import { ResponsiveContainer, BarChart, Bar, LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid, Legend } from "recharts";
import { Badge } from "@/components/ui/badge";
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: number;
  receivingStatus: number;
  costPrice: number;
  notes: string | null;
  leadTimeDays: number | null;
}

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

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 fetch(`${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();
      
      // Transform snake_case to camelCase and convert string numbers to actual numbers
      const transformed: any = {};
      Object.entries(rawData).forEach(([key, value]) => {
        // Better handling of snake_case to camelCase conversion
        let camelKey = key;
        
        // First handle cases like sales_7d -> sales7d
        camelKey = camelKey.replace(/_(\d+[a-z])/g, '$1');
        
        // Then handle regular snake_case -> camelCase
        camelKey = camelKey.replace(/_([a-z])/g, (_, p1) => p1.toUpperCase());
        
        // Convert numeric strings to actual numbers
        if (typeof value === 'string' && !isNaN(Number(value)) && 
            !key.toLowerCase().includes('date') && key !== 'sku' && key !== 'title' && 
            key !== 'brand' && key !== 'vendor') {
          transformed[camelKey] = Number(value);
        } else {
          transformed[camelKey] = value;
        }
      });
      
      // Ensure pid is a number
      transformed.pid = typeof transformed.pid === 'string' ? 
        parseInt(transformed.pid, 10) : transformed.pid;
      
      console.log("Transformed product data:", transformed);
      
      return transformed;
    },
    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 fetch(`${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();
      
      // Ensure the monthly_sales data is properly formatted for charts
      const formattedMonthlySales = data.monthly_sales.map((item: any) => ({
        month: item.month,
        sales: Number(item.sales),
        revenue: Number(item.revenue),
        profit: Number(item.profit || 0)
      }));
      
      return {
        monthlySales: formattedMonthlySales,
        recentPurchases: data.recent_purchases || []
      };
    },
    enabled: !!productId, // Only run query when productId is truthy
  });

  // Get PO status names
  const getPOStatusName = (status: number): string => {
    const statusMap: {[key: number]: string} = {
      0: 'Canceled',
      1: 'Created',
      10: 'Ready to Send',
      11: 'Ordered',
      12: 'Preordered',
      13: 'Electronically Sent',
      15: 'Receiving Started',
      50: 'Completed'
    };
    return statusMap[status] || 'Unknown';
  };

  // Get status badge color class
  const getStatusBadgeClass = (status: number): string => {
    if (status === 0) return "bg-destructive text-destructive-foreground"; // Canceled
    if (status === 50) return "bg-green-600 text-white"; // Completed
    if (status >= 15) return "bg-amber-500 text-black"; // In progress
    return "bg-blue-600 text-white"; // Other statuses
  };

  const isLoading = isLoadingProduct || isLoadingTimeSeries;

  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">
                    {isLoading ? (
                        <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">
                            {isLoading ? <Skeleton className="h-6 w-3/4" /> : product?.title || 'Product Detail'}
                        </VaulDrawer.Title>
                        <VaulDrawer.Description className="text-sm text-muted-foreground">
                            {isLoading ? <Skeleton className="h-4 w-1/2 mt-1" /> : product?.sku || ''}
                        </VaulDrawer.Description>
                         {/* Show Status Badge */}
                         {!isLoading && product && (
                            <div className="mt-1" dangerouslySetInnerHTML={{ __html: getStatusBadge(product.status as ProductStatus) }} />
                         )}
                    </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">
                {isLoading ? (
                    <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)} />
                                     <InfoItem label="Landing Cost" value={formatCurrency(product.currentLandingCostPrice)} />
                                </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" dangerouslySetInnerHTML={{ __html: getStatusBadge(product.status as ProductStatus) }} />} />
                                     <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>
                        </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' || name === 'profit') {
                                                            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" 
                                                />
                                                <Line 
                                                    yAxisId="right"
                                                    type="monotone" 
                                                    dataKey="profit" 
                                                    name="Profit" 
                                                    stroke="#ffc658" 
                                                />
                                            </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>
                            
                            <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>
                            
                            {/* Inventory KPIs Chart */}
                            <Card>
                                <CardHeader>
                                    <CardTitle className="text-base">Key Inventory Metrics</CardTitle>
                                </CardHeader>
                                <CardContent className="h-[250px]">
                                    {isLoading ? (
                                        <Skeleton className="h-[200px] w-full" />
                                    ) : (
                                        <ResponsiveContainer width="100%" height="100%">
                                            <BarChart
                                                data={[
                                                    { 
                                                        name: 'Stock Turn', 
                                                        value: product.stockturn30d || 0,
                                                        fill: '#8884d8' 
                                                    },
                                                    { 
                                                        name: 'GMROI', 
                                                        value: product.gmroi30d || 0, 
                                                        fill: '#82ca9d' 
                                                    },
                                                    { 
                                                        name: 'Sell Through %', 
                                                        value: product.sellThrough30d ? product.sellThrough30d * 100 : 0, 
                                                        fill: '#ffc658' 
                                                    },
                                                    { 
                                                        name: 'Margin %', 
                                                        value: product.margin30d ? product.margin30d * 100 : 0, 
                                                        fill: '#ff8042' 
                                                    }
                                                ]}
                                                margin={{ top: 20, right: 30, left: 20, bottom: 50 }}
                                            >
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="name" angle={-45} textAnchor="end" height={60} />
                                                <YAxis />
                                                <Tooltip
                                                    formatter={(value: number, name: string) => {
                                                        if (name === 'Sell Through %' || name === 'Margin %') {
                                                            return [`${value.toFixed(1)}%`, name];
                                                        }
                                                        return [value.toFixed(2), name];
                                                    }}
                                                />
                                                <Bar dataKey="value" />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    )}
                                </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 ? 
                                            (() => {
                                                const totalOrdered = timeSeriesData.recentPurchases.reduce((acc, po) => acc + po.ordered, 0);
                                                const totalReceived = timeSeriesData.recentPurchases.reduce((acc, po) => acc + po.received, 0);
                                                return totalOrdered > 0 ? formatPercentage(totalReceived / totalOrdered) : '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 => po.status < 50 && po.receivingStatus < 40
                                                ).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="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>
                        </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>
);