/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
'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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { TrendingUp, Fuel, CreditCard, Users, DollarSign, Plus, ShoppingCart, Check, AlertCircle } from 'lucide-react';
import StatCard from '@/components/dashboard/stat-card';

interface SalesData {
  date: string;
  fuelType: string;
  transactions: number;
  liters: number;
  revenue: number;
  avgPrice: number;
  avgLitersPerTx: number;
  loyaltyRate: number;
}

interface FuelStats {
  fuelType: string;
  totalRevenue: number;
  totalLiters: number;
  transactions: number;
  avgPrice: number;
  revenueShare: number;
}

interface PaymentStats {
  method: string;
  count: number;
  percentage: number;
  revenue: number;
}

interface Pump {
  _id: string;
  pumpCode: string;
  fuelTypes: string[];
  location: string;
  cumulativeCounter: number;
}

interface Customer {
  _id: string;
  first_name?: string;
  last_name?: string;
  loyalty_card_id?: string;
}

interface SaleFormData {
  pumpId: string;
  fuelType: string;
  counterStart: number;
  counterEnd: number;
  liters: number;
  unitPrice: number;
  totalAmount: number;
  customerId: string;
  paymentMethod: string;
}

export default function SalesPage() {
  const [period, setPeriod] = useState(30);
  const [salesData, setSalesData] = useState<SalesData[]>([]);
  const [fuelStats, setFuelStats] = useState<FuelStats[]>([]);
  const [paymentStats, setPaymentStats] = useState<PaymentStats[]>([]);
  const [loading, setLoading] = useState(true);
  
  // État pour le formulaire de saisie
  const [pumps, setPumps] = useState<Pump[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [showSaleForm, setShowSaleForm] = useState(false);
  const [saleForm, setSaleForm] = useState<SaleFormData>({
    pumpId: '',
    fuelType: '',
    counterStart: 0,
    counterEnd: 0,
    liters: 0,
    unitPrice: 0,
    totalAmount: 0,
    customerId: 'DIVERS',
    paymentMethod: 'CASH'
  });
  const [submitting, setSubmitting] = useState(false);
  const [submitMessage, setSubmitMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);

  // Prix par défaut par carburant
  const defaultPrices: { [key: string]: number } = {
    'DIESEL': 1.759,
    'SP95': 1.849,
    'SP98': 1.929,
    'E85': 1.089
  };

  useEffect(() => {
    fetchSalesData();
    fetchPumps();
    fetchCustomers();
  }, [period]);

  const fetchSalesData = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/sales/daily?days=${period}`);
      const data = await response.json();
      
      setSalesData(data.dailySales || []);
      setFuelStats(data.fuelStats || []);
      setPaymentStats(data.paymentStats || []);
    } catch (error) {
      console.error('Erreur chargement ventes:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchPumps = async () => {
    try {
      const response = await fetch('/api/pumps');
      const data = await response.json();
      if (data.success) {
        setPumps(data.data);
      }
    } catch (error) {
      console.error('Erreur chargement pompes:', error);
    }
  };

  const fetchCustomers = async () => {
    try {
      const response = await fetch('/api/customers');
      const data = await response.json();
      if (data.success) {
        setCustomers(data.data);
      }
    } catch (error) {
      console.error('Erreur chargement clients:', error);
    }
  };

  const handlePumpChange = (pumpId: string) => {
    const pump = pumps.find(p => p._id === pumpId);
    setSaleForm({
      ...saleForm,
      pumpId,
      fuelType: pump?.fuelTypes[0] || '',
      counterStart: pump?.cumulativeCounter || 0,
      counterEnd: pump?.cumulativeCounter || 0,
      liters: 0,
      unitPrice: pump?.fuelTypes[0] ? defaultPrices[pump.fuelTypes[0]] : 0
    });
  };

  const handleFuelTypeChange = (fuelType: string) => {
    setSaleForm({
      ...saleForm,
      fuelType,
      unitPrice: defaultPrices[fuelType] || 0
    });
    calculateTotal({ ...saleForm, fuelType, unitPrice: defaultPrices[fuelType] || 0 });
  };

  const handleCounterEndChange = (counterEnd: number) => {
    const liters = counterEnd - saleForm.counterStart;
    setSaleForm({ 
      ...saleForm, 
      counterEnd,
      liters: liters > 0 ? parseFloat(liters.toFixed(2)) : 0
    });
    calculateTotal({ 
      ...saleForm, 
      counterEnd,
      liters: liters > 0 ? parseFloat(liters.toFixed(2)) : 0
    });
  };

  const handleUnitPriceChange = (unitPrice: number) => {
    setSaleForm({ ...saleForm, unitPrice });
    calculateTotal({ ...saleForm, unitPrice });
  };

  const calculateTotal = (form: SaleFormData) => {
    const total = form.liters * form.unitPrice;
    setSaleForm({ ...form, totalAmount: parseFloat(total.toFixed(2)) });
  };

  const handleSubmitSale = async () => {
    // Validation
    if (!saleForm.pumpId || !saleForm.fuelType || saleForm.counterEnd <= saleForm.counterStart) {
      setSubmitMessage({ type: 'error', text: 'Le compteur final doit être supérieur au compteur initial' });
      return;
    }

    setSubmitting(true);
    setSubmitMessage(null);

    try {
      const response = await fetch('/api/sales/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(saleForm)
      });

      const data = await response.json();

      if (data.success) {
        setSubmitMessage({ type: 'success', text: 'Vente enregistrée avec succès !' });
        
        // Rafraîchir les pompes AVANT de réinitialiser le formulaire
        await fetchPumps();
        
        // Réinitialiser le formulaire
        setSaleForm({
          pumpId: '',
          fuelType: '',
          counterStart: 0,
          counterEnd: 0,
          liters: 0,
          unitPrice: 0,
          totalAmount: 0,
          customerId: 'DIVERS',
          paymentMethod: 'CASH'
        });
        
        // Rafraîchir les données de ventes
        fetchSalesData();
        
        // Fermer le formulaire après 2 secondes
        setTimeout(() => {
          setShowSaleForm(false);
          setSubmitMessage(null);
        }, 2000);
      } else {
        setSubmitMessage({ type: 'error', text: data.error || 'Erreur lors de l\'enregistrement' });
      }
    } catch (error) {
      setSubmitMessage({ type: 'error', text: 'Erreur de connexion au serveur' });
    } finally {
      setSubmitting(false);
    }
  };

  // Préparer les données pour les graphiques
  const chartData = salesData.reduce((acc: any[], item) => {
    const existingDate = acc.find(d => d.date === item.date);
    if (existingDate) {
      existingDate[item.fuelType] = item.revenue;
      existingDate[`${item.fuelType}_liters`] = item.liters;
    } else {
      acc.push({
        date: new Date(item.date).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' }),
        [item.fuelType]: item.revenue,
        [`${item.fuelType}_liters`]: item.liters,
      });
    }
    return acc;
  }, []);

  const totalRevenue = fuelStats.reduce((sum, stat) => sum + stat.totalRevenue, 0);
  const totalLiters = fuelStats.reduce((sum, stat) => sum + stat.totalLiters, 0);
  const totalTransactions = fuelStats.reduce((sum, stat) => sum + stat.transactions, 0);
  const avgTicket = totalRevenue / totalTransactions || 0;

  const colors = {
    'SP95': '#10b981',
    'SP98': '#3b82f6',
    'DIESEL': '#f59e0b',
    'GPL': '#8b5cf6',
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Ventes Carburant</h1>
          <p className="text-muted-foreground">Analyse détaillée des ventes par carburant</p>
        </div>
        <div className="flex gap-2">
          <Button 
            onClick={() => setShowSaleForm(!showSaleForm)}
            className="bg-green-600 hover:bg-green-700"
          >
            <Plus className="h-4 w-4 mr-2" />
            Nouvelle Vente
          </Button>
          <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>

      {/* Formulaire de saisie de vente */}
      {showSaleForm && (
        <Card className="border-green-500 shadow-lg">
          <CardHeader className="bg-green-50">
            <CardTitle className="flex items-center gap-2">
              <ShoppingCart className="h-5 w-5 text-green-600" />
              Enregistrer une Nouvelle Vente
            </CardTitle>
            <CardDescription>Saisissez les détails de la transaction</CardDescription>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-2 gap-4">
              {/* Sélection Pompe */}
              <div className="space-y-2">
                <Label htmlFor="pump">Pompe *</Label>
                <select
                  id="pump"
                  className="w-full border rounded-md p-2"
                  value={saleForm.pumpId}
                  onChange={(e) => handlePumpChange(e.target.value)}
                >
                  <option value="">-- Sélectionner une pompe --</option>
                  {pumps.map((pump) => (
                    <option key={pump._id} value={pump._id}>
                      {pump.pumpCode} - {pump.location}
                    </option>
                  ))}
                </select>
              </div>

              {/* Sélection Type Carburant */}
              <div className="space-y-2">
                <Label htmlFor="fuelType">Type Carburant *</Label>
                <select
                  id="fuelType"
                  className="w-full border rounded-md p-2"
                  value={saleForm.fuelType}
                  onChange={(e) => handleFuelTypeChange(e.target.value)}
                  disabled={!saleForm.pumpId}
                >
                  <option value="">-- Sélectionner --</option>
                  {saleForm.pumpId && 
                    pumps.find(p => p._id === saleForm.pumpId)?.fuelTypes.map((fuel) => (
                      <option key={fuel} value={fuel}>{fuel}</option>
                    ))
                  }
                </select>
              </div>

              {/* Compteur Initial */}
              <div className="space-y-2">
                <Label htmlFor="counterStart">Compteur Initial (Litres)</Label>
                <Input
                  id="counterStart"
                  type="number"
                  step="0.01"
                  value={saleForm.counterStart.toFixed(2)}
                  disabled
                  className="bg-gray-100 font-semibold"
                />
                <p className="text-xs text-gray-500">Compteur cumulatif actuel de la pompe</p>
              </div>

              {/* Compteur Final */}
              <div className="space-y-2">
                <Label htmlFor="counterEnd">Compteur Final (Litres) *</Label>
                <Input
                  id="counterEnd"
                  type="number"
                  step="0.01"
                  min={saleForm.counterStart}
                  placeholder="0.00"
                  value={saleForm.counterEnd || ''}
                  onChange={(e) => handleCounterEndChange(parseFloat(e.target.value) || 0)}
                  disabled={!saleForm.pumpId}
                />
                <p className="text-xs text-gray-500">Saisir le compteur affiché sur la pompe</p>
              </div>

              {/* Quantité Calculée (Litres) */}
              <div className="space-y-2">
                <Label htmlFor="liters">Quantité Calculée (Litres)</Label>
                <div className="flex items-center">
                  <Input
                    id="liters"
                    type="text"
                    value={saleForm.liters.toFixed(2)}
                    disabled
                    className="bg-blue-50 font-bold text-lg"
                  />
                  <Badge className="ml-2 bg-blue-600">AUTO</Badge>
                </div>
                <p className="text-xs text-gray-500">Calculé: Compteur Final - Compteur Initial</p>
              </div>

              {/* Prix Unitaire */}
              <div className="space-y-2">
                <Label htmlFor="unitPrice">Prix Unitaire (€/L) *</Label>
                <Input
                  id="unitPrice"
                  type="number"
                  step="0.001"
                  min="0"
                  placeholder="0.000"
                  value={saleForm.unitPrice || ''}
                  onChange={(e) => handleUnitPriceChange(parseFloat(e.target.value) || 0)}
                />
              </div>

              {/* Montant Total */}
              <div className="space-y-2">
                <Label htmlFor="totalAmount">Montant Total (€)</Label>
                <div className="flex items-center">
                  <Input
                    id="totalAmount"
                    type="text"
                    value={saleForm.totalAmount.toFixed(2)}
                    disabled
                    className="bg-gray-100 font-bold text-lg"
                  />
                  <Badge className="ml-2 bg-green-600">AUTO</Badge>
                </div>
              </div>

              {/* Client */}
              <div className="space-y-2">
                <Label htmlFor="customer">Client</Label>
                <select
                  id="customer"
                  className="w-full border rounded-md p-2"
                  value={saleForm.customerId}
                  onChange={(e) => setSaleForm({ ...saleForm, customerId: e.target.value })}
                >
                  <option value="DIVERS">Client Divers (par défaut)</option>
                  {customers.map((customer) => (
                    <option key={customer._id} value={customer._id}>
                      {customer.first_name} {customer.last_name} - {customer.loyalty_card_id}
                    </option>
                  ))}
                </select>
              </div>

              {/* Modalité de Paiement */}
              <div className="space-y-2">
                <Label htmlFor="payment">Modalité de Paiement</Label>
                <select
                  id="payment"
                  className="w-full border rounded-md p-2"
                  value={saleForm.paymentMethod}
                  onChange={(e) => setSaleForm({ ...saleForm, paymentMethod: e.target.value })}
                >
                  <option value="CASH">Espèces (par défaut)</option>
                  <option value="CARD">Carte Bancaire</option>
                  <option value="MOBILE">Paiement Mobile</option>
                  <option value="FLEET_CARD">Carte Flotte</option>
                </select>
              </div>

              {/* Message de statut */}
              {submitMessage && (
                <div className="col-span-2">
                  <div className={`p-4 rounded-md flex items-center gap-2 ${
                    submitMessage.type === 'success' 
                      ? 'bg-green-100 text-green-800 border border-green-300' 
                      : 'bg-red-100 text-red-800 border border-red-300'
                  }`}>
                    {submitMessage.type === 'success' ? (
                      <Check className="h-5 w-5" />
                    ) : (
                      <AlertCircle className="h-5 w-5" />
                    )}
                    {submitMessage.text}
                  </div>
                </div>
              )}

              {/* Boutons */}
              <div className="col-span-2 flex justify-end gap-3 mt-4">
                <Button 
                  variant="outline" 
                  onClick={() => {
                    setShowSaleForm(false);
                    setSubmitMessage(null);
                  }}
                >
                  Annuler
                </Button>
                <Button 
                  onClick={handleSubmitSale}
                  disabled={submitting}
                  className="bg-green-600 hover:bg-green-700"
                >
                  {submitting ? 'Enregistrement...' : 'Enregistrer la Vente'}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* KPIs */}
      <div className="grid gap-4 md:grid-cols-4">
        <StatCard
          title="Chiffre d'Affaires"
          value={`${totalRevenue.toLocaleString('fr-FR')} €`}
          icon={DollarSign}
          trend={{ value: 12.5, isPositive: true }}
        />
        <StatCard
          title="Volume Vendu"
          value={`${totalLiters.toLocaleString('fr-FR')} L`}
          icon={Fuel}
          trend={{ value: 8.3, isPositive: true }}
        />
        <StatCard
          title="Transactions"
          value={totalTransactions.toLocaleString('fr-FR')}
          icon={Users}
          trend={{ value: -2.1, isPositive: false }}
        />
        <StatCard
          title="Ticket Moyen"
          value={`${avgTicket.toFixed(2)} €`}
          icon={TrendingUp}
          trend={{ value: 5.7, isPositive: true }}
        />
      </div>

      {/* Graphiques */}
      <Tabs defaultValue="revenue" className="space-y-4">
        <TabsList>
          <TabsTrigger value="revenue">Chiffre d&apos;Affaires</TabsTrigger>
          <TabsTrigger value="volume">Volume</TabsTrigger>
          <TabsTrigger value="transactions">Transactions</TabsTrigger>
          <TabsTrigger value="payment">Paiements</TabsTrigger>
        </TabsList>

        {/* CA par carburant */}
        <TabsContent value="revenue">
          <Card>
            <CardHeader>
              <CardTitle>Évolution du Chiffre d&apos;Affaires</CardTitle>
              <CardDescription>CA quotidien par type de carburant</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={400}>
                <LineChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => `${value.toFixed(2)} €`} />
                  <Legend />
                  {fuelStats.map(fuel => (
                    <Line
                      key={fuel.fuelType}
                      type="monotone"
                      dataKey={fuel.fuelType}
                      stroke={colors[fuel.fuelType as keyof typeof colors] || '#888'}
                      name={fuel.fuelType}
                      strokeWidth={2}
                    />
                  ))}
                </LineChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Volume par carburant */}
        <TabsContent value="volume">
          <Card>
            <CardHeader>
              <CardTitle>Évolution des Volumes</CardTitle>
              <CardDescription>Litres vendus quotidiennement par carburant</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={400}>
                <BarChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => `${value.toFixed(0)} L`} />
                  <Legend />
                  {fuelStats.map(fuel => (
                    <Bar
                      key={fuel.fuelType}
                      dataKey={`${fuel.fuelType}_liters`}
                      fill={colors[fuel.fuelType as keyof typeof colors] || '#888'}
                      name={fuel.fuelType}
                    />
                  ))}
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Stats détaillées par carburant */}
        <TabsContent value="transactions">
          <Card>
            <CardHeader>
              <CardTitle>Détails par Carburant</CardTitle>
              <CardDescription>Performance détaillée 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">Carburant</th>
                      <th className="p-2 text-right">Transactions</th>
                      <th className="p-2 text-right">Volume (L)</th>
                      <th className="p-2 text-right">CA (€)</th>
                      <th className="p-2 text-right">Prix Moy.</th>
                      <th className="p-2 text-right">Part CA</th>
                    </tr>
                  </thead>
                  <tbody>
                    {fuelStats.map((fuel) => (
                      <tr key={fuel.fuelType} className="border-b hover:bg-muted/50">
                        <td className="p-2 font-medium">{fuel.fuelType}</td>
                        <td className="p-2 text-right">{fuel.transactions.toLocaleString('fr-FR')}</td>
                        <td className="p-2 text-right">{fuel.totalLiters.toLocaleString('fr-FR')}</td>
                        <td className="p-2 text-right">{fuel.totalRevenue.toLocaleString('fr-FR')} €</td>
                        <td className="p-2 text-right">{fuel.avgPrice.toFixed(3)} €/L</td>
                        <td className="p-2 text-right">
                          <span className="text-primary font-medium">
                            {fuel.revenueShare.toFixed(1)}%
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Paiements */}
        <TabsContent value="payment">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Répartition Paiements</CardTitle>
                <CardDescription>Modes de paiement utilisés</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {paymentStats.map((payment) => (
                    <div key={payment.method} className="space-y-2">
                      <div className="flex items-center justify-between text-sm">
                        <span className="flex items-center gap-2">
                          <CreditCard className="h-4 w-4" />
                          {payment.method}
                        </span>
                        <span className="font-medium">{payment.percentage.toFixed(1)}%</span>
                      </div>
                      <div className="h-2 bg-muted rounded-full overflow-hidden">
                        <div
                          className="h-full bg-primary"
                          style={{ width: `${payment.percentage}%` }}
                        />
                      </div>
                      <div className="flex justify-between text-xs text-muted-foreground">
                        <span>{payment.count} transactions</span>
                        <span>{payment.revenue.toLocaleString('fr-FR')} €</span>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Top Horaires</CardTitle>
                <CardDescription>Heures de pointe</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {[
                    { hour: '07:00 - 09:00', transactions: 45, revenue: 2340 },
                    { hour: '12:00 - 14:00', transactions: 38, revenue: 1980 },
                    { hour: '17:00 - 19:00', transactions: 52, revenue: 2650 },
                    { hour: '19:00 - 21:00', transactions: 28, revenue: 1450 },
                  ].map((slot) => (
                    <div key={slot.hour} className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <div className="font-medium">{slot.hour}</div>
                        <div className="text-sm text-muted-foreground">
                          {slot.transactions} transactions
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="font-bold text-primary">{slot.revenue} €</div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
