'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 { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { Users, TrendingUp, DollarSign, Calendar, Search } from 'lucide-react';
import StatCard from '@/components/dashboard/stat-card';

interface Customer {
  customerId: string;
  loyaltyCardId: string;
  firstName: string;
  lastName: string;
  segment: string;
  registrationDate: string;
  fuelTxCount: number;
  shopTxCount: number;
  totalSpent: number;
  totalFuelLiters: number;
  avgTxPerMonth: number;
  lastVisitDate: string;
  daysSinceLastVisit: number;
  status: 'ACTIVE' | 'AT_RISK' | 'CHURNED';
}

interface CustomerStats {
  totalCustomers: number;
  activeCustomers: number;
  atRiskCustomers: number;
  churnedCustomers: number;
  avgSpentPerCustomer: number;
  avgVisitFrequency: number;
}

interface SegmentData {
  segment: string;
  count: number;
  revenue: number;
  avgSpent: number;
}

export default function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [stats, setStats] = useState<CustomerStats | null>(null);
  const [segments, setSegments] = useState<SegmentData[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  useEffect(() => {
    const loadData = async () => {
      try {
        const response = await fetch('/api/customers/loyalty');
        const data = await response.json();
        
        setCustomers(data.customers || []);
        setStats(data.stats || null);
        setSegments(data.segments || []);
      } catch (error) {
        console.error('Erreur chargement clients:', error);
      }
    };
    
    loadData();
  }, []);

  const filteredCustomers = customers.filter(customer => {
    const matchesSearch = 
      customer.firstName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      customer.lastName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      customer.loyaltyCardId.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = filterStatus === 'all' || customer.status === filterStatus;
    
    return matchesSearch && matchesStatus;
  });

  const getStatusColor = (status: string): "default" | "secondary" | "destructive" | "outline" => {
    switch (status) {
      case 'ACTIVE': return 'default';
      case 'AT_RISK': return 'secondary';
      case 'CHURNED': return 'destructive';
      default: return 'outline';
    }
  };

  const getSegmentColor = (segment: string): "default" | "secondary" | "destructive" | "outline" => {
    switch (segment) {
      case 'VIP': return 'default';
      case 'GOLD': return 'default';
      case 'SILVER': return 'secondary';
      default: return 'outline';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold">Clients & Fidélité</h1>
        <p className="text-muted-foreground">Analyse comportementale et segmentation RFM</p>
      </div>

      {/* KPIs */}
      <div className="grid gap-4 md:grid-cols-4">
        <StatCard
          title="Clients Actifs"
          value={stats?.activeCustomers.toLocaleString('fr-FR') || '0'}
          icon={Users}
          trend={{ value: 12.5, isPositive: true }}
        />
        <StatCard
          title="Clients à Risque"
          value={stats?.atRiskCustomers.toLocaleString('fr-FR') || '0'}
          icon={TrendingUp}
          trend={{ value: -5.2, isPositive: true }}
        />
        <StatCard
          title="Dépense Moyenne"
          value={`${stats?.avgSpentPerCustomer.toFixed(2) || '0'} €`}
          icon={DollarSign}
          trend={{ value: 8.3, isPositive: true }}
        />
        <StatCard
          title="Fréquence Visites"
          value={`${stats?.avgVisitFrequency.toFixed(1) || '0'} /mois`}
          icon={Calendar}
          trend={{ value: 3.7, isPositive: true }}
        />
      </div>

      {/* Contenu principal */}
      <Tabs defaultValue="customers" className="space-y-4">
        <TabsList>
          <TabsTrigger value="customers">Base Clients</TabsTrigger>
          <TabsTrigger value="segments">Segmentation</TabsTrigger>
          <TabsTrigger value="retention">Rétention</TabsTrigger>
          <TabsTrigger value="insights">Insights</TabsTrigger>
        </TabsList>

        {/* Liste clients */}
        <TabsContent value="customers">
          <Card>
            <CardHeader>
              <CardTitle>Base Clients Fidélité</CardTitle>
              <CardDescription>
                {filteredCustomers.length} client(s) sur {customers.length}
              </CardDescription>
              <div className="flex gap-4 mt-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Rechercher par nom ou carte..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <div className="flex gap-2">
                  <Badge
                    variant={filterStatus === 'all' ? 'default' : 'outline'}
                    className="cursor-pointer"
                    onClick={() => setFilterStatus('all')}
                  >
                    Tous
                  </Badge>
                  <Badge
                    variant={filterStatus === 'ACTIVE' ? 'default' : 'outline'}
                    className="cursor-pointer"
                    onClick={() => setFilterStatus('ACTIVE')}
                  >
                    Actifs
                  </Badge>
                  <Badge
                    variant={filterStatus === 'AT_RISK' ? 'default' : 'outline'}
                    className="cursor-pointer"
                    onClick={() => setFilterStatus('AT_RISK')}
                  >
                    À Risque
                  </Badge>
                  <Badge
                    variant={filterStatus === 'CHURNED' ? 'default' : 'outline'}
                    className="cursor-pointer"
                    onClick={() => setFilterStatus('CHURNED')}
                  >
                    Perdus
                  </Badge>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="p-2 text-left">Client</th>
                      <th className="p-2 text-left">Carte</th>
                      <th className="p-2 text-left">Segment</th>
                      <th className="p-2 text-left">Statut</th>
                      <th className="p-2 text-right">Transactions</th>
                      <th className="p-2 text-right">CA Total</th>
                      <th className="p-2 text-right">Dernière Visite</th>
                      <th className="p-2 text-right">Fréquence</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredCustomers.slice(0, 50).map((customer) => (
                      <tr key={customer.customerId} className="border-b hover:bg-muted/50">
                        <td className="p-2">
                          <div>
                            <div className="font-medium">
                              {customer.firstName} {customer.lastName}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              Depuis {new Date(customer.registrationDate).toLocaleDateString('fr-FR')}
                            </div>
                          </div>
                        </td>
                        <td className="p-2 font-mono text-sm">{customer.loyaltyCardId}</td>
                        <td className="p-2">
                          <Badge variant={getSegmentColor(customer.segment)}>
                            {customer.segment}
                          </Badge>
                        </td>
                        <td className="p-2">
                          <Badge variant={getStatusColor(customer.status)}>
                            {customer.status}
                          </Badge>
                        </td>
                        <td className="p-2 text-right">
                          <div className="text-sm">
                            {customer.fuelTxCount + customer.shopTxCount}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {customer.fuelTxCount}C + {customer.shopTxCount}S
                          </div>
                        </td>
                        <td className="p-2 text-right font-medium">
                          {customer.totalSpent.toFixed(2)} €
                        </td>
                        <td className="p-2 text-right">
                          <div className="text-sm">
                            {new Date(customer.lastVisitDate).toLocaleDateString('fr-FR')}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            Il y a {customer.daysSinceLastVisit}j
                          </div>
                        </td>
                        <td className="p-2 text-right">
                          {customer.avgTxPerMonth.toFixed(1)} /mois
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Segmentation */}
        <TabsContent value="segments">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Répartition par Segment</CardTitle>
                <CardDescription>Distribution de la base clients</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={segments}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="segment" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="count" fill="#10b981" name="Nombre de clients" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>CA par Segment</CardTitle>
                <CardDescription>Contribution au chiffre d&apos;affaires</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={segments}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="segment" />
                    <YAxis />
                    <Tooltip formatter={(value: number) => `${value.toFixed(2)} €`} />
                    <Legend />
                    <Bar dataKey="revenue" fill="#3b82f6" name="CA (€)" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Tableau segments */}
          <Card className="mt-4">
            <CardHeader>
              <CardTitle>Détails par Segment</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="p-2 text-left">Segment</th>
                      <th className="p-2 text-right">Clients</th>
                      <th className="p-2 text-right">CA Total</th>
                      <th className="p-2 text-right">Dépense Moyenne</th>
                      <th className="p-2 text-right">% Base</th>
                      <th className="p-2 text-right">% CA</th>
                    </tr>
                  </thead>
                  <tbody>
                    {segments.map((segment) => (
                      <tr key={segment.segment} className="border-b hover:bg-muted/50">
                        <td className="p-2">
                          <Badge variant={getSegmentColor(segment.segment)}>
                            {segment.segment}
                          </Badge>
                        </td>
                        <td className="p-2 text-right">{segment.count}</td>
                        <td className="p-2 text-right font-medium">
                          {segment.revenue.toFixed(2)} €
                        </td>
                        <td className="p-2 text-right">{segment.avgSpent.toFixed(2)} €</td>
                        <td className="p-2 text-right">
                          {((segment.count / (stats?.totalCustomers || 1)) * 100).toFixed(1)}%
                        </td>
                        <td className="p-2 text-right">
                          <span className="text-primary font-medium">
                            {((segment.revenue / segments.reduce((sum, s) => sum + s.revenue, 0)) * 100).toFixed(1)}%
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Rétention */}
        <TabsContent value="retention">
          <div className="grid gap-4">
            <Card>
              <CardHeader>
                <CardTitle>Évolution de la Rétention</CardTitle>
                <CardDescription>Taux de rétention mensuel des cohortes</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart
                    data={[
                      { month: 'Jan', retention: 100, active: 85 },
                      { month: 'Fév', retention: 85, active: 72 },
                      { month: 'Mar', retention: 72, active: 65 },
                      { month: 'Avr', retention: 65, active: 60 },
                      { month: 'Mai', retention: 60, active: 57 },
                      { month: 'Jun', retention: 57, active: 55 },
                    ]}
                  >
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Line type="monotone" dataKey="retention" stroke="#10b981" name="Rétention (%)" />
                    <Line type="monotone" dataKey="active" stroke="#3b82f6" name="Actifs (%)" />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <div className="grid gap-4 md:grid-cols-3">
              <Card>
                <CardHeader>
                  <CardTitle>Taux de Churn</CardTitle>
                  <CardDescription>Clients perdus sur 30j</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-3xl font-bold text-destructive">
                    {((stats?.churnedCustomers || 0) / (stats?.totalCustomers || 1) * 100).toFixed(1)}%
                  </div>
                  <p className="text-sm text-muted-foreground mt-2">
                    {stats?.churnedCustomers || 0} clients inactifs
                  </p>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>Clients à Réactiver</CardTitle>
                  <CardDescription>Inactifs 30-90 jours</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-3xl font-bold text-orange-600">
                    {stats?.atRiskCustomers || 0}
                  </div>
                  <p className="text-sm text-muted-foreground mt-2">
                    Opportunité de reconquête
                  </p>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>LTV Moyenne</CardTitle>
                  <CardDescription>Lifetime Value client</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-3xl font-bold text-green-600">
                    {stats?.avgSpentPerCustomer.toFixed(2) || 0} €
                  </div>
                  <p className="text-sm text-muted-foreground mt-2">
                    Par client actif
                  </p>
                </CardContent>
              </Card>
            </div>
          </div>
        </TabsContent>

        {/* Insights */}
        <TabsContent value="insights">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Actions Recommandées</CardTitle>
                <CardDescription>Campagnes de fidélisation</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {[
                    {
                      segment: 'VIP',
                      count: 45,
                      action: 'Programme exclusif',
                      impact: 'Haute',
                    },
                    {
                      segment: 'À Risque',
                      count: stats?.atRiskCustomers || 0,
                      action: 'Offre de réactivation',
                      impact: 'Moyenne',
                    },
                    {
                      segment: 'Nouveaux',
                      count: 28,
                      action: 'Welcome pack',
                      impact: 'Moyenne',
                    },
                    {
                      segment: 'Perdus',
                      count: stats?.churnedCustomers || 0,
                      action: 'Enquête satisfaction',
                      impact: 'Faible',
                    },
                  ].map((item, idx) => (
                    <div key={idx} className="p-4 border rounded-lg space-y-2">
                      <div className="flex items-center justify-between">
                        <div className="font-medium">{item.segment}</div>
                        <Badge variant={item.impact === 'Haute' ? 'default' : 'secondary'}>
                          {item.count} clients
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">{item.action}</p>
                      <div className="text-sm text-primary font-medium">
                        Impact: {item.impact}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Opportunités Cross-Selling</CardTitle>
                <CardDescription>Produits complémentaires</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="p-4 bg-primary/10 rounded-lg">
                    <div className="font-medium mb-2">Clients Carburant Seulement</div>
                    <div className="text-2xl font-bold">
                      {customers.filter(c => c.fuelTxCount > 0 && c.shopTxCount === 0).length}
                    </div>
                    <p className="text-sm text-muted-foreground mt-2">
                      Opportunité shop: café, snacks
                    </p>
                  </div>

                  <div className="p-4 bg-green-500/10 rounded-lg">
                    <div className="font-medium mb-2">Clients Multi-Produits</div>
                    <div className="text-2xl font-bold text-green-600">
                      {customers.filter(c => c.fuelTxCount > 0 && c.shopTxCount > 0).length}
                    </div>
                    <p className="text-sm text-muted-foreground mt-2">
                      Panier moyen: +35% vs mono-produit
                    </p>
                  </div>

                  <div className="p-4 bg-orange-500/10 rounded-lg">
                    <div className="font-medium mb-2">Potentiel Carte Lavage</div>
                    <div className="text-2xl font-bold text-orange-600">
                      {Math.floor(customers.length * 0.6)}
                    </div>
                    <p className="text-sm text-muted-foreground mt-2">
                      60% des clients cibles
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
