'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { ShoppingCart, TrendingUp, Package, DollarSign } from 'lucide-react';
import StatCard from '@/components/dashboard/stat-card';

interface ShopData {
  totalRevenue: number;
  transactions: number;
  avgBasket: number;
  itemsSold: number;
  avgItemsPerBasket: number;
  loyaltyRate: number;
}

interface TopProduct {
  productCode: string;
  productName: string;
  category: string;
  subCategory: string;
  quantity: number;
  revenue: number;
  transactions: number;
  avgPrice: number;
  margin: number;
  penetration: number;
}

interface CategoryStats {
  category: string;
  subCategory: string;
  quantity: number;
  revenue: number;
  transactions: number;
  revenueShare: number;
  [key: string]: string | number;
}

export default function ShopPage() {
  const [period, setPeriod] = useState(30);
  const [shopData, setShopData] = useState<ShopData | null>(null);
  const [topProducts, setTopProducts] = useState<TopProduct[]>([]);
  const [categoryStats, setCategoryStats] = useState<CategoryStats[]>([]);

  useEffect(() => {
    fetchShopData();
  }, [period]);

  const fetchShopData = async () => {
    try {
      const response = await fetch(`/api/shop/performance?days=${period}`);
      const data = await response.json();
      
      setShopData(data.overview || null);
      setTopProducts(data.topProducts || []);
      setCategoryStats(data.categoryStats || []);
    } catch (error) {
      console.error('Erreur chargement shop:', error);
    }
  };

  const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6', '#ec4899', '#06b6d4'];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Performance Boutique</h1>
          <p className="text-muted-foreground">Analyse des ventes shop et optimisation assortiment</p>
        </div>
        <div className="flex gap-2">
          <Select value={period.toString()} onValueChange={(v) => setPeriod(Number(v))}>
            <option value="7">7 jours</option>
            <option value="30">30 jours</option>
            <option value="90">90 jours</option>
          </Select>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid gap-4 md:grid-cols-4">
        <StatCard
          title="CA Boutique"
          value={`${shopData?.totalRevenue.toLocaleString('fr-FR') || '0'} €`}
          icon={DollarSign}
          trend={{ value: 15.2, isPositive: true }}
        />
        <StatCard
          title="Panier Moyen"
          value={`${shopData?.avgBasket.toFixed(2) || '0'} €`}
          icon={ShoppingCart}
          trend={{ value: 8.7, isPositive: true }}
        />
        <StatCard
          title="Articles Vendus"
          value={shopData?.itemsSold.toLocaleString('fr-FR') || '0'}
          icon={Package}
          trend={{ value: 12.3, isPositive: true }}
        />
        <StatCard
          title="Taux Fidélité"
          value={`${shopData?.loyaltyRate.toFixed(1) || '0'}%`}
          icon={TrendingUp}
          trend={{ value: 3.5, isPositive: true }}
        />
      </div>

      {/* Contenu principal */}
      <Tabs defaultValue="products" className="space-y-4">
        <TabsList>
          <TabsTrigger value="products">Top Produits</TabsTrigger>
          <TabsTrigger value="categories">Catégories</TabsTrigger>
          <TabsTrigger value="margins">Marges</TabsTrigger>
          <TabsTrigger value="insights">Insights</TabsTrigger>
        </TabsList>

        {/* Top 20 Produits */}
        <TabsContent value="products">
          <Card>
            <CardHeader>
              <CardTitle>Top 20 Produits par Chiffre d&apos;Affaires</CardTitle>
              <CardDescription>Meilleurs produits sur {period} jours</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="p-2 text-left">Produit</th>
                      <th className="p-2 text-left">Catégorie</th>
                      <th className="p-2 text-right">Qté</th>
                      <th className="p-2 text-right">CA</th>
                      <th className="p-2 text-right">Prix Moy.</th>
                      <th className="p-2 text-right">Marge</th>
                      <th className="p-2 text-right">Pénétration</th>
                    </tr>
                  </thead>
                  <tbody>
                    {topProducts.slice(0, 20).map((product, idx) => (
                      <tr key={product.productCode} className="border-b hover:bg-muted/50">
                        <td className="p-2">
                          <div>
                            <div className="font-medium">{product.productName}</div>
                            <div className="text-xs text-muted-foreground">{product.productCode}</div>
                          </div>
                        </td>
                        <td className="p-2">
                          <Badge variant={idx < 5 ? "default" : "secondary"}>
                            {product.category}
                          </Badge>
                        </td>
                        <td className="p-2 text-right">{product.quantity}</td>
                        <td className="p-2 text-right font-medium">{product.revenue.toFixed(2)} €</td>
                        <td className="p-2 text-right">{product.avgPrice.toFixed(2)} €</td>
                        <td className="p-2 text-right">
                          <span className="text-green-600 font-medium">
                            {product.margin?.toFixed(2) || 'N/A'} €
                          </span>
                        </td>
                        <td className="p-2 text-right">
                          <span className="text-primary">{product.penetration.toFixed(1)}%</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Catégories */}
        <TabsContent value="categories">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Répartition par Catégorie</CardTitle>
                <CardDescription>Part du CA boutique</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={categoryStats}
                      dataKey="revenue"
                      nameKey="category"
                      cx="50%"
                      cy="50%"
                      outerRadius={100}
                      label
                    >
                      {categoryStats.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(value: number) => `${value.toFixed(2)} €`} />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Performance par Catégorie</CardTitle>
                <CardDescription>Volume et CA</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={categoryStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="category" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="revenue" fill="#10b981" name="CA (€)" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Tableau détaillé */}
          <Card className="mt-4">
            <CardHeader>
              <CardTitle>Détails par Sous-Catégorie</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="p-2 text-left">Catégorie</th>
                      <th className="p-2 text-left">Sous-Catégorie</th>
                      <th className="p-2 text-right">Quantité</th>
                      <th className="p-2 text-right">CA</th>
                      <th className="p-2 text-right">Transactions</th>
                      <th className="p-2 text-right">Part CA</th>
                    </tr>
                  </thead>
                  <tbody>
                    {categoryStats.map((cat, idx) => (
                      <tr key={idx} className="border-b hover:bg-muted/50">
                        <td className="p-2 font-medium">{cat.category}</td>
                        <td className="p-2 text-muted-foreground">{cat.subCategory}</td>
                        <td className="p-2 text-right">{cat.quantity}</td>
                        <td className="p-2 text-right font-medium">{cat.revenue.toFixed(2)} €</td>
                        <td className="p-2 text-right">{cat.transactions}</td>
                        <td className="p-2 text-right">
                          <span className="text-primary font-medium">
                            {cat.revenueShare.toFixed(1)}%
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Marges */}
        <TabsContent value="margins">
          <Card>
            <CardHeader>
              <CardTitle>Analyse des Marges</CardTitle>
              <CardDescription>Rentabilité par produit</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="p-2 text-left">Produit</th>
                      <th className="p-2 text-right">CA</th>
                      <th className="p-2 text-right">Marge Brute</th>
                      <th className="p-2 text-right">Taux Marge</th>
                      <th className="p-2 text-right">Impact</th>
                    </tr>
                  </thead>
                  <tbody>
                    {topProducts
                      .filter(p => p.margin && p.margin > 0)
                      .sort((a, b) => (b.margin || 0) - (a.margin || 0))
                      .slice(0, 15)
                      .map((product) => {
                        const marginRate = ((product.margin || 0) / product.revenue) * 100;
                        return (
                          <tr key={product.productCode} className="border-b hover:bg-muted/50">
                            <td className="p-2">
                              <div className="font-medium">{product.productName}</div>
                              <div className="text-xs text-muted-foreground">{product.category}</div>
                            </td>
                            <td className="p-2 text-right">{product.revenue.toFixed(2)} €</td>
                            <td className="p-2 text-right">
                              <span className="text-green-600 font-medium">
                                {product.margin?.toFixed(2)} €
                              </span>
                            </td>
                            <td className="p-2 text-right">
                              <Badge variant={marginRate > 40 ? "default" : "secondary"}>
                                {marginRate.toFixed(1)}%
                              </Badge>
                            </td>
                            <td className="p-2 text-right">
                              <div className="h-2 bg-muted rounded-full w-24 ml-auto overflow-hidden">
                                <div
                                  className="h-full bg-green-500"
                                  style={{ width: `${Math.min(marginRate, 100)}%` }}
                                />
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Insights */}
        <TabsContent value="insights">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Recommandations</CardTitle>
                <CardDescription>Actions suggérées</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {[
                    {
                      type: 'success',
                      title: 'Produits Performants',
                      description: 'Les sandwiches génèrent 35% du CA boutique',
                      action: 'Augmenter le stock de 20%',
                    },
                    {
                      type: 'warning',
                      title: 'Stock à Optimiser',
                      description: 'Chips en rupture 3x cette semaine',
                      action: 'Revoir les seuils de commande',
                    },
                    {
                      type: 'info',
                      title: 'Opportunité',
                      description: 'Forte demande café 07h-09h',
                      action: 'Promotion petit-déjeuner',
                    },
                    {
                      type: 'warning',
                      title: 'Produits Lents',
                      description: '12 références < 1 vente/jour',
                      action: 'Envisager déréférencement',
                    },
                  ].map((insight, idx) => (
                    <div key={idx} className="p-4 border rounded-lg space-y-2">
                      <div className="flex items-center gap-2">
                        <Badge
                          variant={
                            insight.type === 'success'
                              ? 'default'
                              : insight.type === 'warning'
                              ? 'destructive'
                              : 'secondary'
                          }
                        >
                          {insight.type}
                        </Badge>
                        <span className="font-medium">{insight.title}</span>
                      </div>
                      <p className="text-sm text-muted-foreground">{insight.description}</p>
                      <p className="text-sm text-primary font-medium">→ {insight.action}</p>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Métriques Clés</CardTitle>
                <CardDescription>Indicateurs de performance</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>Taux de Rotation</span>
                      <span className="font-medium">85%</span>
                    </div>
                    <div className="h-2 bg-muted rounded-full overflow-hidden">
                      <div className="h-full bg-green-500" style={{ width: '85%' }} />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>Taux de Rupture</span>
                      <span className="font-medium text-orange-600">4.2%</span>
                    </div>
                    <div className="h-2 bg-muted rounded-full overflow-hidden">
                      <div className="h-full bg-orange-500" style={{ width: '4.2%' }} />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>Marge Moyenne</span>
                      <span className="font-medium text-green-600">42%</span>
                    </div>
                    <div className="h-2 bg-muted rounded-full overflow-hidden">
                      <div className="h-full bg-green-500" style={{ width: '42%' }} />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span>Cross-Selling (Carburant+Shop)</span>
                      <span className="font-medium">28%</span>
                    </div>
                    <div className="h-2 bg-muted rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500" style={{ width: '28%' }} />
                    </div>
                  </div>

                  <div className="mt-6 p-4 bg-primary/10 rounded-lg">
                    <div className="text-sm font-medium mb-2">Objectif du Mois</div>
                    <div className="flex items-baseline gap-2">
                      <span className="text-2xl font-bold">
                        {shopData?.totalRevenue.toLocaleString('fr-FR') || '0'}€
                      </span>
                      <span className="text-sm text-muted-foreground">/ 25,000€</span>
                    </div>
                    <div className="mt-2 h-2 bg-muted rounded-full overflow-hidden">
                      <div
                        className="h-full bg-primary"
                        style={{
                          width: `${Math.min(((shopData?.totalRevenue || 0) / 25000) * 100, 100)}%`,
                        }}
                      />
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
