import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import {
  ArrowLeft, Edit, Copy, Package, Tag, Box, BarChart3, Euro,
  Building2, Truck, Calendar, Hash, Scale, Percent, AlertTriangle,
  CheckCircle, XCircle, MoreVertical,
  PlusCircle
} from 'lucide-react';
import Tabs from '@/components/Tabs';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { cn } from '@/lib/utils';
import { useAppSelector } from '@/store/hooks';
import { getArticleSelected } from '@/store/features/article/selectors';
import { Article } from '@/types/articleType';
import { toast } from '@/components/ui/use-toast';
import { ModalArticle } from '@/components/modal/ModalArticle';
import { ModalStock } from '@/components/modal/ModalStock';

// Composants réutilisables
const InfoRow = ({ label, value, mono = false }: { label: string; value?: string | number | null; mono?: boolean }) => {
  if (value === null || value === undefined || value === '') return null;
  return (
    <div>
      <p className="text-xs text-gray-500 uppercase mb-1">{label}</p>
      <p className={cn("font-medium text-gray-900 dark:text-white", mono && "font-mono")}>{value}</p>
    </div>
  );
};

const StatCard = ({ label, value, color, icon: Icon }: { label: string; value: string | number; color: string; icon?: any }) => (
  <div className={cn("p-4 rounded-xl border", color)}>
    <div className="flex items-center justify-between">
      <p className="text-xs uppercase font-bold opacity-80">{label}</p>
      {Icon && <Icon className="w-4 h-4 opacity-60" />}
    </div>
    <p className="text-2xl font-bold mt-1">{value}</p>
  </div>
);

const SectionCard = ({ icon: Icon, title, children, className = "" }: { icon: any; title: string; children: React.ReactNode; className?: string }) => (
  <div className={cn("bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6", className)}>
    <h3 className="text-lg font-bold mb-4 flex items-center gap-2 text-gray-900 dark:text-white">
      <Icon className="w-5 h-5 text-[#007E45]" /> {title}
    </h3>
    {children}
  </div>
);

const ArticleDetailPage = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('details');
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isEditModalStockOpen, setIsEditModalStockOpen] = useState(false);
  const [editing, setEditing] = useState<Article | null>(null);


  const article = useAppSelector(getArticleSelected) as Article;
  console.log("article ! ",article);
  
  if (!article) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-500">Article non trouvé</p>
      </div>
    );
  }

  const tabs = [
    { id: 'details', label: 'Détails Article' },
    { id: 'pricing', label: 'Tarification' },
    { id: 'stock', label: 'Stock & Logistique' },
    { id: 'history', label: 'Historique' },
  ];

  // Calculs
  const marge = article.prix_achat && article.prix_vente
    ? ((article.prix_vente - article.prix_achat) / article.prix_vente * 100)
    : null;

  const stockMax = article.stock_maxi || 100;
  const stockPercent = Math.min((article.stock_reel / stockMax) * 100, 100);
  const isLowStock = article.stock_mini && article.stock_reel < article.stock_mini;

  const getBadges = () => {
    const badges = [];
    if (article.est_actif === false) badges.push({ label: 'Inactif', color: 'bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-300' });
    if (article.en_sommeil) badges.push({ label: 'En sommeil', color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-300' });
    if (isLowStock) badges.push({ label: 'Stock bas', color: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-300' });
    return badges;
  };

  const handleCopyReference = () => {
    navigator.clipboard.writeText(article.reference);
    toast({ title: "Copié", description: "Référence copiée dans le presse-papier" });
  };

  const handleEdit = (row: Article) => {
    setEditing(row);
    setIsEditModalOpen(true);
  };

  const handleStock = (row: Article) => {
    setEditing(row);
    setIsEditModalStockOpen(true);
  };

  return (
    <>
      <Helmet>
        <title>{article.reference} - {article.designation} - Dataven</title>
      </Helmet>

      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col gap-4">
          <button
            onClick={() => navigate('/home/articles')}
            className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors w-fit"
          >
            <ArrowLeft className="w-4 h-4" />
            Retour au articles
          </button>

          <div className="flex flex-col md:flex-row md:items-start justify-between gap-4 bg-white dark:bg-gray-950 p-6 rounded-2xl border border-gray-200 dark:border-gray-800">
            <div className="flex items-start gap-4">
              <div style={{ width: "7vh", height: "7vh" }} className="w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-900 flex items-center justify-center shadow-sm text-gray-400">
                <Package className="w-8 h-8" />
              </div>
              <div>
                <div className="flex items-center gap-3 mb-1">
                  <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{article.designation}</h1>
                  {article.est_actif !== false ? (
                    <span className="px-2 py-0.5 bg-green-100 dark:bg-green-900/20 text-green-700 dark:text-green-300 rounded-lg text-xs font-medium flex items-center gap-1">
                      <CheckCircle className="w-3 h-3" /> Actif
                    </span>
                  ) : (
                    <span className="px-2 py-0.5 bg-red-100 dark:bg-red-900/20 text-red-700 dark:text-red-300 rounded-lg text-xs font-medium flex items-center gap-1">
                      <XCircle className="w-3 h-3" /> Inactif
                    </span>
                  )}
                </div>

                {article.designation_complementaire && (
                  <p className="text-gray-600 dark:text-gray-400 text-sm mb-2">{article.designation_complementaire}</p>
                )}

                <div className="flex flex-wrap items-center gap-3 text-sm">
                  <span className="font-mono bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded text-xs text-gray-700 dark:text-gray-300">
                    {article.reference}
                  </span>
                  {article.famille_libelle && (
                    <span className="px-2 py-0.5 bg-purple-100 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300 rounded text-xs">
                      {article.famille_libelle}
                    </span>
                  )}
                  {article.type_article_libelle && (
                    <span className="px-2 py-0.5 bg-blue-100 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded text-xs">
                      {article.type_article_libelle}
                    </span>
                  )}
                  <span className={cn(
                    "font-medium",
                    isLowStock ? "text-green-600" : "text-gray-600 dark:text-gray-400"
                  )}>
                    Stock: <strong>{article.stock_reel}</strong> {article.unite_vente || 'unités'}
                  </span>
                </div>

                <div className="flex flex-wrap items-center gap-2 mt-3">
                  {getBadges().map((badge, i) => (
                    <span key={i} className={cn("px-2.5 py-0.5 rounded-lg text-xs font-medium", badge.color)}>
                      {badge.label}
                    </span>
                  ))}
                </div>
              </div>
            </div>

            <div className="flex gap-3">
              <button
                onClick={handleCopyReference}
                className="p-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                title="Copier la référence"
              >
                <Copy className="w-5 h-5" />
              </button>
              <PrimaryButton_v2 icon={PlusCircle} onClick={() => handleStock(article)}>
                Stock
              </PrimaryButton_v2>
              <PrimaryButton_v2 icon={Edit} onClick={() => handleEdit(article)}>
                Modifier
              </PrimaryButton_v2>
              <button
                className="p-2.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400"
                title="More options"
              >
                <MoreVertical className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>

        <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />

        <div className="mt-6">
          {activeTab === 'details' && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <SectionCard icon={Tag} title="Identification">
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <InfoRow label="Référence" value={article.reference} mono />
                    <InfoRow label="Code EAN" value={article.code_ean} mono />
                    <InfoRow label="Code Barre" value={article.code_barre} mono />
                    <InfoRow label="Famille" value={article.famille_libelle || article.famille_code} />
                    <InfoRow label="Type article" value={article.type_article_libelle} />
                    <InfoRow label="Unité de vente" value={article.unite_vente} />
                  </div>

                  {article.description && (
                    <div className="pt-4 border-t border-gray-100 dark:border-gray-800">
                      <p className="text-xs text-gray-500 uppercase mb-2">Description</p>
                      <p className="text-gray-900 dark:text-gray-300 bg-gray-50 dark:bg-gray-900 p-3 rounded-lg text-sm">
                        {article.description}
                      </p>
                    </div>
                  )}
                </div>
              </SectionCard>

              <div className="space-y-6">
                <SectionCard icon={BarChart3} title="Aperçu rapide">
                  <div className="grid grid-cols-2 gap-4">
                    <StatCard
                      label="Prix de vente HT"
                      value={`${article.prix_vente.toFixed(2)} €`}
                      color="bg-green-50 dark:bg-green-900/20 border-green-100 dark:border-green-800 text-green-700 dark:text-green-300"
                      icon={Euro}
                    />
                    <StatCard
                      label="Stock disponible"
                      value={article.stock_disponible ?? article.stock_reel}
                      color={isLowStock
                        ? "bg-red-50 dark:bg-red-900/20 border-red-100 dark:border-red-800 text-red-700 dark:text-red-300"
                        : "bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-800 text-blue-700 dark:text-blue-300"
                      }
                      icon={Box}
                    />
                  </div>
                </SectionCard>

                {article.fournisseur_nom && (
                  <SectionCard icon={Truck} title="Fournisseur principal">
                    <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-900 rounded-xl">
                      <div className="w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400">
                        <Building2 className="w-5 h-5" />
                      </div>
                      <div>
                        <p className="font-medium text-gray-900 dark:text-white">{article.fournisseur_nom}</p>
                        {article.fournisseur_principal && (
                          <p className="text-xs text-gray-500 font-mono">{article.fournisseur_principal}</p>
                        )}
                      </div>
                    </div>
                    {article.unite_achat && (
                      <p className="text-sm text-gray-500 mt-3">
                        Unité d'achat: <span className="font-medium text-gray-700 dark:text-gray-300">{article.unite_achat}</span>
                      </p>
                    )}
                  </SectionCard>
                )}

                {(article.poids || article.volume) && (
                  <SectionCard icon={Scale} title="Caractéristiques physiques">
                    <div className="grid grid-cols-2 gap-4">
                      <InfoRow label="Poids" value={article.poids ? `${article.poids} kg` : null} />
                      <InfoRow label="Volume" value={article.volume ? `${article.volume} m³` : null} />
                    </div>
                  </SectionCard>
                )}
              </div>
            </div>
          )}

          {activeTab === 'pricing' && (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <SectionCard icon={Euro} title="Prix et Marges" className="lg:col-span-2">
                <div className="grid grid-cols-3 gap-8 mb-8">
                  <div>
                    <p className="text-sm text-gray-500 mb-1">Prix d'achat</p>
                    <p className="text-xl font-bold text-gray-900 dark:text-white">
                      {article.prix_achat ? `${article.prix_achat.toFixed(2)} €` : '-'}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500 mb-1">Prix de vente HT</p>
                    <p className="text-xl font-bold text-[#007E45]">{article.prix_vente.toFixed(2)} €</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500 mb-1">Marge</p>
                    <p className={cn("text-xl font-bold", marge && marge > 0 ? "text-green-600" : "text-gray-400")}>
                      {marge ? `${marge.toFixed(1)}%` : '-'}
                    </p>
                  </div>
                </div>

                {article.prix_revient && (
                  <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-xl mb-6">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600 dark:text-gray-400">Prix de revient</span>
                      <span className="font-bold text-gray-900 dark:text-white">{article.prix_revient.toFixed(2)} €</span>
                    </div>
                  </div>
                )}

                <div className="pt-6 border-t border-gray-100 dark:border-gray-800">
                  <h4 className="font-semibold mb-4 flex items-center gap-2">
                    <Percent className="w-4 h-4 text-gray-400" /> TVA & Comptabilité
                  </h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg">
                      <span className="text-gray-500">Code TVA</span>
                      <span className="font-mono font-medium">{article.tva_code || '-'}</span>
                    </div>
                    <div className="flex justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg">
                      <span className="text-gray-500">Taux TVA</span>
                      <span className="font-medium">{article.tva_taux ? `${article.tva_taux}%` : '-'}</span>
                    </div>
                  </div>
                </div>
              </SectionCard>

              <SectionCard icon={BarChart3} title="Rentabilité">
                <div className="space-y-4">
                  <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-100 dark:border-blue-800">
                    <p className="text-xs text-blue-600 dark:text-blue-400 uppercase font-bold">Ventes 30j</p>
                    <p className="text-2xl font-bold text-blue-700 dark:text-blue-300 mt-1">-</p>
                  </div>
                  <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-100 dark:border-green-800">
                    <p className="text-xs text-green-600 dark:text-green-400 uppercase font-bold">CA Généré</p>
                    <p className="text-2xl font-bold text-green-700 dark:text-green-300 mt-1">-</p>
                  </div>
                </div>
              </SectionCard>
            </div>
          )}

          {activeTab === 'stock' && (
            <div className="space-y-6">
              <SectionCard icon={Box} title="État des stocks">
                <div className="flex items-center gap-4 mb-6">
                  <Box className="w-8 h-8 text-gray-400" />
                  <div>
                    <h4 className="font-bold text-gray-900 dark:text-white">Stock global</h4>
                    <p className="text-sm text-gray-500">Tous entrepôts confondus</p>
                  </div>
                  {isLowStock && (
                    <div className="ml-auto flex items-center gap-2 px-3 py-1.5 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 rounded-lg text-sm font-medium">
                      <AlertTriangle className="w-4 h-4" />
                      Stock bas
                    </div>
                  )}
                </div>

                <div className="w-full bg-gray-100 dark:bg-gray-900 rounded-full h-4 mb-2 overflow-hidden">
                  <div
                    className={cn(
                      "h-full rounded-full transition-all",
                      isLowStock ? "bg-red-500" : "bg-blue-500"
                    )}
                    style={{ width: `${stockPercent}%` }}
                  />
                </div>
                <div className="flex justify-between text-sm text-gray-500 mb-6">
                  <span>0</span>
                  <span>Stock actuel: <strong className={isLowStock ? "text-red-600" : ""}>{article.stock_reel}</strong></span>
                  <span>Max: {stockMax}</span>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-5 gap-4 border-t border-gray-100 dark:border-gray-800 pt-6">
                  <div>
                    <p className="text-xs text-gray-500 uppercase font-bold">Stock réel</p>
                    <p className="text-xl font-bold">{article.stock_reel}</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase font-bold">Disponible</p>
                    <p className="text-xl font-bold text-green-600">{article.stock_disponible ?? article.stock_reel}</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase font-bold">Réservé</p>
                    <p className="text-xl font-bold text-orange-500">{article.stock_reserve ?? 0}</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase font-bold">En commande</p>
                    <p className="text-xl font-bold text-blue-500">{article.stock_commande ?? 0}</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 uppercase font-bold">Stock mini</p>
                    <p className="text-xl font-bold text-gray-400">{article.stock_mini ?? '-'}</p>
                  </div>
                </div>
              </SectionCard>

              {(article.unite_vente || article.unite_achat || article.poids || article.volume) && (
                <SectionCard icon={Scale} title="Logistique">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <InfoRow label="Unité de vente" value={article.unite_vente} />
                    <InfoRow label="Unité d'achat" value={article.unite_achat} />
                    <InfoRow label="Poids" value={article.poids ? `${article.poids} kg` : null} />
                    <InfoRow label="Volume" value={article.volume ? `${article.volume} m³` : null} />
                  </div>
                </SectionCard>
              )}
            </div>
          )}

          {activeTab === 'history' && (
            <SectionCard icon={Calendar} title="Historique">
              <div className="grid grid-cols-2 gap-4 mb-6">
                <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-xl">
                  <p className="text-xs text-gray-500 uppercase mb-1">Date de création</p>
                  <p className="font-medium text-gray-900 dark:text-white">
                    {article.date_creation ? new Date(article.date_creation).toLocaleDateString('fr-FR', {
                      day: 'numeric', month: 'long', year: 'numeric'
                    }) : '-'}
                  </p>
                </div>
                <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-xl">
                  <p className="text-xs text-gray-500 uppercase mb-1">Dernière modification</p>
                  <p className="font-medium text-gray-900 dark:text-white">
                    {article.date_modification ? new Date(article.date_modification).toLocaleDateString('fr-FR', {
                      day: 'numeric', month: 'long', year: 'numeric'
                    }) : '-'}
                  </p>
                </div>
              </div>

              <div className="text-center py-8 bg-gray-50 dark:bg-gray-900 rounded-xl border border-dashed border-gray-200 dark:border-gray-800">
                <Calendar className="w-10 h-10 text-gray-300 mx-auto mb-2" />
                <p className="text-gray-500">Aucun mouvement de stock récent</p>
                <p className="text-sm text-gray-400 mt-1">L'historique des mouvements apparaîtra ici</p>
              </div>
            </SectionCard>
          )}
        </div>
        <ModalArticle
          open={isEditModalOpen}
          onClose={() => setIsEditModalOpen(false)}
          title={editing ? `Mettre à jour l'article ${editing.reference}` : "Crée une article"}
          editing={editing}
        />

        <ModalStock
          open={isEditModalStockOpen}
          onClose={() => setIsEditModalStockOpen(false)}
          title={editing ? `Mettre à jour le stock de l'article ${editing.reference}` : "Ajouter stock"}
          editing={editing}
        />
      </div>

    </>
  );
};

export default ArticleDetailPage;