'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Database, AlertTriangle, TrendingDown, TrendingUp } from 'lucide-react';
import { Progress } from '@/components/ui/progress';

interface StockStatus {
  tank: {
    id: string;
    code: string;
    fuelType: string;
    capacity: number;
    minLevel: number;
  };
  currentLevel: number;
  fillRate: number;
  avgDailyConsumption: number;
  daysOfStock: number | null;
  status: 'NORMAL' | 'LOW' | 'CRITICAL' | 'HIGH';
  lastReading: string | null;
  lastDelivery: string | null;
  temperature: number | null;
}

const statusConfig = {
  NORMAL: { color: 'bg-green-500', label: 'Normal', badge: 'default' as const },
  LOW: { color: 'bg-yellow-500', label: 'Bas', badge: 'secondary' as const },
  CRITICAL: { color: 'bg-red-500', label: 'Critique', badge: 'destructive' as const },
  HIGH: { color: 'bg-blue-500', label: 'Élevé', badge: 'outline' as const },
};

export default function StocksPage() {
  const [stocks, setStocks] = useState<StockStatus[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchStocks();
    const interval = setInterval(fetchStocks, 60000); // Refresh chaque minute
    return () => clearInterval(interval);
  }, []);

  const fetchStocks = async () => {
    try {
      const response = await fetch('/api/stocks/status');
      const result = await response.json();
      if (result.success) {
        setStocks(result.data);
      }
    } catch (error) {
      console.error('Erreur chargement stocks:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <div className="h-12 w-12 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"></div>
          <p className="mt-4 text-muted-foreground">Chargement des stocks...</p>
        </div>
      </div>
    );
  }

  const criticalTanks = stocks.filter((s) => s.status === 'CRITICAL');
  const lowTanks = stocks.filter((s) => s.status === 'LOW');

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Gestion des Stocks</h1>
          <p className="text-muted-foreground">Suivi des niveaux de cuves en temps réel</p>
        </div>
        <button
          onClick={fetchStocks}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
        >
          Actualiser
        </button>
      </div>

      {/* Alertes */}
      {(criticalTanks.length > 0 || lowTanks.length > 0) && (
        <Card className="border-red-500">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-red-500" />
              Alertes Stock
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {criticalTanks.length > 0 && (
              <div className="text-red-600">
                {criticalTanks.length} cuve(s) en niveau critique
              </div>
            )}
            {lowTanks.length > 0 && (
              <div className="text-yellow-600">
                {lowTanks.length} cuve(s) en niveau bas
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Stock Cards */}
      <div className="grid gap-6 md:grid-cols-2">
        {stocks.map((stock) => {
          const config = statusConfig[stock.status];

          return (
            <Card key={stock.tank.id} className="relative overflow-hidden">
              <div
                className={`absolute top-0 left-0 w-1 h-full ${config.color}`}
              />
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      <Database className="h-5 w-5" />
                      {stock.tank.code}
                    </CardTitle>
                    <p className="text-sm text-muted-foreground mt-1">
                      {stock.tank.fuelType}
                    </p>
                  </div>
                  <Badge variant={config.badge}>{config.label}</Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Jauge de remplissage */}
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span>Niveau actuel</span>
                    <span className="font-medium">
                      {Math.round(stock.currentLevel).toLocaleString()} L
                    </span>
                  </div>
                  <Progress value={stock.fillRate} className="h-3" />
                  <div className="flex justify-between text-xs text-muted-foreground">
                    <span>0 L</span>
                    <span>{stock.fillRate.toFixed(1)}%</span>
                    <span>{stock.tank.capacity.toLocaleString()} L</span>
                  </div>
                </div>

                {/* Statistiques */}
                <div className="grid grid-cols-2 gap-4 pt-2 border-t">
                  <div>
                    <p className="text-xs text-muted-foreground">
                      Consommation moy.
                    </p>
                    <p className="text-sm font-medium flex items-center gap-1">
                      <TrendingDown className="h-3 w-3 text-red-500" />
                      {Math.round(stock.avgDailyConsumption).toLocaleString()} L/j
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">Autonomie</p>
                    <p className="text-sm font-medium">
                      {stock.daysOfStock !== null
                        ? `${stock.daysOfStock.toFixed(1)} jours`
                        : 'N/A'}
                    </p>
                  </div>
                  {stock.temperature && (
                    <div>
                      <p className="text-xs text-muted-foreground">Température</p>
                      <p className="text-sm font-medium">
                        {stock.temperature.toFixed(1)}°C
                      </p>
                    </div>
                  )}
                  <div>
                    <p className="text-xs text-muted-foreground">Seuil min.</p>
                    <p className="text-sm font-medium">
                      {stock.tank.minLevel.toLocaleString()} L
                    </p>
                  </div>
                </div>

                {/* Dernières actions */}
                <div className="pt-2 border-t text-xs text-muted-foreground">
                  {stock.lastReading && (
                    <p>
                      Dernière lecture:{' '}
                      {new Date(stock.lastReading).toLocaleString('fr-FR')}
                    </p>
                  )}
                  {stock.lastDelivery && (
                    <p>
                      Dernière livraison:{' '}
                      {new Date(stock.lastDelivery).toLocaleString('fr-FR')}
                    </p>
                  )}
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
