'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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 { Package, Plus, Edit, Trash2, TrendingDown, AlertCircle, Image as ImageIcon } from 'lucide-react';

interface Product {
  _id: string;
  productCode: string;
  productName: string;
  category: string;
  subCategory?: string;
  description?: string;
  unit: string;
  purchasePrice?: number;
  salePrice?: number;
  currentStock?: number;
  minStock?: number;
  barcode?: string;
  imageUrl?: string;
  supplierId?: { _id: string; supplierName: string };
  active: boolean;
}

interface Supplier {
  _id: string;
  supplierName: string;
}

const CATEGORIES = [
  { value: 'LUBRICANTS', label: 'Huiles/Lubrifiants', color: 'bg-orange-100 text-orange-800' },
  { value: 'FILTERS', label: 'Filtres', color: 'bg-yellow-100 text-yellow-800' },
  { value: 'PARTS', label: 'Pièces Auto', color: 'bg-blue-100 text-blue-800' },
  { value: 'ACCESSORIES', label: 'Accessoires', color: 'bg-purple-100 text-purple-800' },
  { value: 'FOOD', label: 'Alimentation', color: 'bg-green-100 text-green-800' },
  { value: 'BEVERAGES', label: 'Boissons', color: 'bg-cyan-100 text-cyan-800' },
  { value: 'TOBACCO', label: 'Tabac', color: 'bg-red-100 text-red-800' },
  { value: 'OTHER', label: 'Autres', color: 'bg-gray-100 text-gray-800' },
];

const UNITS = ['PIECE', 'LITER', 'KILOGRAM', 'BOX', 'PACK'];

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [formData, setFormData] = useState({
    productCode: '',
    productName: '',
    category: 'LUBRICANTS',
    subCategory: '',
    description: '',
    unit: 'PIECE',
    purchasePrice: '',
    salePrice: '',
    currentStock: '',
    minStock: '',
    barcode: '',
    imageUrl: '',
    supplierId: '',
  });
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
  const [filterCategory, setFilterCategory] = useState<string>('ALL');

  useEffect(() => {
    fetchProducts();
    fetchSuppliers();
  }, []);

  const fetchProducts = async () => {
    try {
      const response = await fetch('/api/products');
      const data = await response.json();
      if (data.success) {
        setProducts(data.data);
      }
    } catch (error) {
      console.error('Erreur chargement produits:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchSuppliers = async () => {
    try {
      const response = await fetch('/api/suppliers');
      const data = await response.json();
      if (data.success) {
        setSuppliers(data.data.filter((s: Supplier & {active: boolean}) => s.active));
      }
    } catch (error) {
      console.error('Erreur chargement fournisseurs:', error);
    }
  };

  const handleOpenModal = (product?: Product) => {
    if (product) {
      setEditingProduct(product);
      setFormData({
        productCode: product.productCode,
        productName: product.productName,
        category: product.category,
        subCategory: product.subCategory || '',
        description: product.description || '',
        unit: product.unit,
        purchasePrice: product.purchasePrice?.toString() || '',
        salePrice: product.salePrice?.toString() || '',
        currentStock: product.currentStock?.toString() || '',
        minStock: product.minStock?.toString() || '',
        barcode: product.barcode || '',
        imageUrl: product.imageUrl || '',
        supplierId: product.supplierId?._id || '',
      });
    } else {
      setEditingProduct(null);
      setFormData({
        productCode: '',
        productName: '',
        category: 'LUBRICANTS',
        subCategory: '',
        description: '',
        unit: 'PIECE',
        purchasePrice: '',
        salePrice: '',
        currentStock: '0',
        minStock: '0',
        barcode: '',
        imageUrl: '',
        supplierId: '',
      });
    }
    setShowModal(true);
    setMessage(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setMessage(null);

    try {
      const url = editingProduct 
        ? `/api/products/${editingProduct._id}`
        : '/api/products';
      
      const method = editingProduct ? 'PUT' : 'POST';

      const payload = {
        ...formData,
        purchasePrice: formData.purchasePrice ? parseFloat(formData.purchasePrice) : 0,
        salePrice: formData.salePrice ? parseFloat(formData.salePrice) : 0,
        currentStock: formData.currentStock ? parseFloat(formData.currentStock) : 0,
        minStock: formData.minStock ? parseFloat(formData.minStock) : 0,
        supplierId: formData.supplierId || null,
      };

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await response.json();

      if (data.success) {
        setMessage({ type: 'success', text: data.message });
        await fetchProducts();
        setTimeout(() => {
          setShowModal(false);
          setMessage(null);
        }, 1500);
      } else {
        setMessage({ type: 'error', text: data.error });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Erreur de connexion au serveur' });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Êtes-vous sûr de vouloir supprimer le produit "${name}" ?`)) {
      return;
    }

    try {
      const response = await fetch(`/api/products/${id}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (data.success) {
        await fetchProducts();
      } else {
        alert(data.error);
      }
    } catch (error) {
      alert('Erreur lors de la suppression');
    }
  };

  const getCategoryInfo = (category: string) => {
    return CATEGORIES.find(c => c.value === category) || CATEGORIES[CATEGORIES.length - 1];
  };

  const calculateMargin = (purchase?: number, sale?: number) => {
    if (!purchase || !sale || purchase === 0) return 0;
    return ((sale - purchase) / purchase * 100).toFixed(1);
  };

  const filteredProducts = filterCategory === 'ALL' 
    ? products 
    : products.filter(p => p.category === filterCategory);

  if (loading) {
    return <div className="p-8">Chargement...</div>;
  }

  return (
    <div className="p-8 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Gestion des Articles</h1>
          <p className="text-muted-foreground mt-1">
            Gérez vos produits: huiles, filtres, pièces, alimentation...
          </p>
        </div>
        <Button onClick={() => handleOpenModal()} className="gap-2">
          <Plus className="h-4 w-4" />
          Nouvel Article
        </Button>
      </div>

      {/* Filtres */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex gap-2 flex-wrap">
            <Button
              variant={filterCategory === 'ALL' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setFilterCategory('ALL')}
            >
              Tous ({products.length})
            </Button>
            {CATEGORIES.map(cat => {
              const count = products.filter(p => p.category === cat.value).length;
              return (
                <Button
                  key={cat.value}
                  variant={filterCategory === cat.value ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setFilterCategory(cat.value)}
                >
                  {cat.label} ({count})
                </Button>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Liste des produits */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {filteredProducts.map((product) => {
          const categoryInfo = getCategoryInfo(product.category);
          const margin = calculateMargin(product.purchasePrice, product.salePrice);
          const lowStock = (product.currentStock || 0) <= (product.minStock || 0);

          return (
            <Card key={product._id} className={!product.active ? 'opacity-50' : ''}>
              <CardHeader className="pb-3">
                <div className="flex justify-between items-start gap-2">
                  <div className="flex-1 min-w-0">
                    <CardTitle className="flex items-center gap-2 text-base">
                      {product.imageUrl ? (
                        <img src={product.imageUrl} alt={product.productName} className="h-8 w-8 object-cover rounded" />
                      ) : (
                        <Package className="h-5 w-5 flex-shrink-0" />
                      )}
                      <span className="truncate">{product.productName}</span>
                    </CardTitle>
                    <CardDescription className="mt-1 text-xs">
                      Réf: {product.productCode}
                    </CardDescription>
                  </div>
                  <Badge className={`${categoryInfo.color} text-xs flex-shrink-0`}>
                    {categoryInfo.label}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                {product.description && (
                  <p className="text-xs text-muted-foreground line-clamp-2">{product.description}</p>
                )}

                <div className="grid grid-cols-2 gap-2 text-xs">
                  <div>
                    <span className="text-muted-foreground">Achat:</span>
                    <div className="font-semibold">{product.purchasePrice?.toFixed(2) || '0.00'}€</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Vente:</span>
                    <div className="font-semibold text-green-600">{product.salePrice?.toFixed(2) || '0.00'}€</div>
                  </div>
                </div>

                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted-foreground">Marge:</span>
                  <Badge variant="outline" className="text-xs">
                    {margin}%
                  </Badge>
                </div>

                <div className={`flex items-center gap-2 p-2 rounded ${lowStock ? 'bg-red-50' : 'bg-green-50'}`}>
                  {lowStock && <AlertCircle className="h-4 w-4 text-red-600" />}
                  <div className="flex-1">
                    <div className="text-xs text-muted-foreground">Stock actuel</div>
                    <div className={`font-bold ${lowStock ? 'text-red-600' : 'text-green-600'}`}>
                      {product.currentStock || 0} {product.unit}
                    </div>
                  </div>
                  {lowStock && (
                    <TrendingDown className="h-4 w-4 text-red-600" />
                  )}
                </div>

                {product.supplierId && (
                  <div className="text-xs text-muted-foreground">
                    Fournisseur: {product.supplierId.supplierName}
                  </div>
                )}

                <div className="flex gap-2 pt-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleOpenModal(product)}
                    className="flex-1 text-xs"
                  >
                    <Edit className="h-3 w-3 mr-1" />
                    Modifier
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleDelete(product._id, product.productName)}
                    className="text-red-600 hover:text-red-700"
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {filteredProducts.length === 0 && (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            Aucun produit trouvé
          </CardContent>
        </Card>
      )}

      {/* Modal Ajout/Modification */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4 overflow-y-auto">
          <Card className="w-full max-w-3xl my-8">
            <CardHeader className="bg-blue-50">
              <CardTitle>
                {editingProduct ? 'Modifier le Produit' : 'Nouvel Article'}
              </CardTitle>
              <CardDescription>
                Remplissez les informations du produit
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 pt-6 max-h-[70vh] overflow-y-auto">
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="productCode">Code Article *</Label>
                    <Input
                      id="productCode"
                      value={formData.productCode}
                      onChange={(e) => setFormData({ ...formData, productCode: e.target.value.toUpperCase() })}
                      placeholder="HUILE-5W30"
                      required
                      disabled={!!editingProduct}
                    />
                  </div>
                  <div>
                    <Label htmlFor="barcode">Code-barre</Label>
                    <Input
                      id="barcode"
                      value={formData.barcode}
                      onChange={(e) => setFormData({ ...formData, barcode: e.target.value })}
                      placeholder="3456789012345"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="productName">Désignation *</Label>
                  <Input
                    id="productName"
                    value={formData.productName}
                    onChange={(e) => setFormData({ ...formData, productName: e.target.value })}
                    placeholder="Huile Moteur 5W30 Castrol Edge"
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="description">Description</Label>
                  <textarea
                    id="description"
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    placeholder="Description détaillée du produit..."
                    className="w-full px-3 py-2 border rounded-md min-h-[60px]"
                  />
                </div>

                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="category">Catégorie *</Label>
                    <select
                      id="category"
                      value={formData.category}
                      onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                      className="w-full px-3 py-2 border rounded-md"
                      required
                    >
                      {CATEGORIES.map(cat => (
                        <option key={cat.value} value={cat.value}>{cat.label}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <Label htmlFor="subCategory">Sous-catégorie</Label>
                    <Input
                      id="subCategory"
                      value={formData.subCategory}
                      onChange={(e) => setFormData({ ...formData, subCategory: e.target.value })}
                      placeholder="Ex: Synthétique"
                    />
                  </div>
                  <div>
                    <Label htmlFor="unit">Unité *</Label>
                    <select
                      id="unit"
                      value={formData.unit}
                      onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                      className="w-full px-3 py-2 border rounded-md"
                      required
                    >
                      {UNITS.map(unit => (
                        <option key={unit} value={unit}>{unit}</option>
                      ))}
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="purchasePrice">Prix d'Achat (€) *</Label>
                    <Input
                      id="purchasePrice"
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.purchasePrice}
                      onChange={(e) => setFormData({ ...formData, purchasePrice: e.target.value })}
                      placeholder="25.50"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="salePrice">Prix de Vente (€) *</Label>
                    <Input
                      id="salePrice"
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.salePrice}
                      onChange={(e) => setFormData({ ...formData, salePrice: e.target.value })}
                      placeholder="35.90"
                      required
                    />
                  </div>
                </div>

                {formData.purchasePrice && formData.salePrice && (
                  <div className="p-3 bg-blue-50 rounded">
                    <div className="text-sm font-medium">
                      Marge: {calculateMargin(parseFloat(formData.purchasePrice), parseFloat(formData.salePrice))}%
                      {' '}
                      ({(parseFloat(formData.salePrice) - parseFloat(formData.purchasePrice)).toFixed(2)}€)
                    </div>
                  </div>
                )}

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="currentStock">Stock Actuel</Label>
                    <Input
                      id="currentStock"
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.currentStock}
                      onChange={(e) => setFormData({ ...formData, currentStock: e.target.value })}
                      placeholder="50"
                    />
                  </div>
                  <div>
                    <Label htmlFor="minStock">Stock Minimum</Label>
                    <Input
                      id="minStock"
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.minStock}
                      onChange={(e) => setFormData({ ...formData, minStock: e.target.value })}
                      placeholder="10"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="supplierId">Fournisseur</Label>
                  <select
                    id="supplierId"
                    value={formData.supplierId}
                    onChange={(e) => setFormData({ ...formData, supplierId: e.target.value })}
                    className="w-full px-3 py-2 border rounded-md"
                  >
                    <option value="">-- Aucun --</option>
                    {suppliers.map(supplier => (
                      <option key={supplier._id} value={supplier._id}>
                        {supplier.supplierName}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <Label htmlFor="imageUrl" className="flex items-center gap-2">
                    <ImageIcon className="h-4 w-4" />
                    URL de l'Image
                  </Label>
                  <Input
                    id="imageUrl"
                    value={formData.imageUrl}
                    onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
                    placeholder="https://example.com/image.jpg"
                  />
                  {formData.imageUrl && (
                    <div className="mt-2">
                      <img 
                        src={formData.imageUrl} 
                        alt="Aperçu" 
                        className="h-20 w-20 object-cover rounded border"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                        }}
                      />
                    </div>
                  )}
                </div>

                {message && (
                  <div className={`p-3 rounded ${
                    message.type === 'success' ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'
                  }`}>
                    {message.text}
                  </div>
                )}

                <div className="flex gap-2 pt-4 sticky bottom-0 bg-white pb-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setShowModal(false);
                      setMessage(null);
                    }}
                    disabled={submitting}
                    className="flex-1"
                  >
                    Annuler
                  </Button>
                  <Button
                    type="submit"
                    disabled={submitting}
                    className="flex-1"
                  >
                    {submitting ? 'Enregistrement...' : 'Enregistrer'}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
