import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card';
import { InventoryValueTrend } from '../components/analytics/InventoryValueTrend';
import { InventoryFlow } from '../components/analytics/InventoryFlow';
import { InventoryTrends } from '../components/analytics/InventoryTrends';
import { PortfolioAnalysis } from '../components/analytics/PortfolioAnalysis';
import { CapitalEfficiency } from '../components/analytics/CapitalEfficiency';
import { StockHealth } from '../components/analytics/StockHealth';
import { AgingSellThrough } from '../components/analytics/AgingSellThrough';
import { StockoutRisk } from '../components/analytics/StockoutRisk';
import { SeasonalPatterns } from '../components/analytics/SeasonalPatterns';
import { DiscountImpact } from '../components/analytics/DiscountImpact';
import { GrowthMomentum } from '../components/analytics/GrowthMomentum';
import config from '../config';
import { motion } from 'motion/react';
import { DollarSign, RefreshCw, TrendingUp, Calendar } from 'lucide-react';
import { formatCurrency } from '../utils/formatCurrency';

interface InventorySummary {
  stockInvestment: number;
  onOrderValue: number;
  inventoryTurns: number;
  gmroi: number;
  avgStockCoverDays: number;
  productsInStock: number;
  deadStockProducts: number;
  deadStockValue: number;
}

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

  return (
    <motion.div layout className="flex-1 space-y-6 p-8 pt-6">
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">Analytics</h2>
      </div>

      {/* KPI Summary Cards */}
      {isError && (
        <Card>
          <CardContent className="py-4">
            <p className="text-sm text-destructive">Failed to load inventory summary</p>
          </CardContent>
        </Card>
      )}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Stock Investment</CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading || !summary ? (
              <div className="h-8 w-24 animate-pulse rounded bg-muted" />
            ) : (
              <>
                <div className="text-2xl font-bold">{formatCurrency(summary.stockInvestment)}</div>
                <p className="text-xs text-muted-foreground">
                  {formatCurrency(summary.onOrderValue)} on order
                </p>
              </>
            )}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Inventory Turns</CardTitle>
            <RefreshCw className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading || !summary ? (
              <div className="h-8 w-24 animate-pulse rounded bg-muted" />
            ) : (
              <>
                <div className="text-2xl font-bold">{summary.inventoryTurns.toFixed(1)}x</div>
                <p className="text-xs text-muted-foreground">annualized (30d basis)</p>
              </>
            )}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">GMROI</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading || !summary ? (
              <div className="h-8 w-24 animate-pulse rounded bg-muted" />
            ) : (
              <>
                <div className="text-2xl font-bold">{summary.gmroi.toFixed(2)}</div>
                <p className="text-xs text-muted-foreground">
                  annualized profit per $ invested
                </p>
              </>
            )}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Median Stock Cover</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading || !summary ? (
              <div className="h-8 w-24 animate-pulse rounded bg-muted" />
            ) : (
              <>
                <div className="text-2xl font-bold">{Math.round(summary.avgStockCoverDays)} days</div>
                <p className="text-xs text-muted-foreground">
                  {summary.productsInStock.toLocaleString()} products in stock
                </p>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Section 2: Inventory Value Over Time */}
      <InventoryValueTrend />

      {/* Section 3: Inventory Flow — Receiving vs Selling */}
      <InventoryFlow />

      {/* Section 4: Daily Sales Activity & Stockouts */}
      <InventoryTrends />

      {/* Section 5: ABC Portfolio Analysis */}
      <PortfolioAnalysis />

      {/* Section 6: Capital Efficiency */}
      <CapitalEfficiency />

      {/* Section 7: Demand & Stock Health */}
      <StockHealth />

      {/* Section 8: Aging & Sell-Through */}
      <AgingSellThrough />

      {/* Section 9: Reorder Risk */}
      <StockoutRisk />

      {/* Section 10: Seasonal Patterns */}
      <SeasonalPatterns />

      {/* Section 11: Discount Impact */}
      <DiscountImpact />

      {/* Section 12: YoY Growth Momentum */}
      <GrowthMomentum />
    </motion.div>
  );
}
