
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { ArrowLeft, Edit, Copy, Trash2, Layers, Package, Info } from 'lucide-react';
import { mockProductFamilies, mockArticles, CompanyInfo } from '@/data/mockData';
import StatusBadge from '@/components/StatusBadget';
import Tabs from '@/components/Tabs';
import DataTable from '@/components/DataTable';
import ProductFamilyFormModal from '@/components/forms/ProductFamilyFormModal';
import { cn } from '@/lib/utils';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getfamilleSelected } from '@/store/features/famille/selectors';
import { Famille } from '@/types/familleType';
import { Article } from '@/types/articleType';
import { articleStatus, getAllArticles } from '@/store/features/article/selectors';
import { getArticles } from '@/store/features/article/thunk';
import { selectArticle } from '@/store/features/article/slice';
import StatusBadgetLettre from '@/components/StatusBadgetLettre';

const ProductFamilyDetailPage = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [activeTab, setActiveTab] = useState('details');
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

  const articles = useAppSelector(getAllArticles) as Article[];
  const statusArticle = useAppSelector(articleStatus)
  const famille = useAppSelector(getfamilleSelected) as Famille
  if (!famille) return <div>Famille introuvable</div>;

  const isLoading = statusArticle === 'loading' && articles.length === 0;

  useEffect(() => {
    const load = async () => {
      if (statusArticle === "idle") await dispatch(getArticles()).unwrap();
    }
    load()
  }, [statusArticle, dispatch])

  const articleFiltered = articles.filter(item => item.famille_code === famille.code)

  const tabs = [
    { id: 'details', label: 'Détails' },
    { id: 'articles', label: 'Articles associés' },
    { id: 'timeline', label: 'Historique' },
  ];

  return (
    <>
      <Helmet>
        <title>{famille.code} - {CompanyInfo.name}</title>
      </Helmet>

      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col gap-4">
          <button
            onClick={() => navigate('/home/familles-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 aux familles
          </button>

          <div className="flex flex-col md:flex-row md:items-start justify-between gap-4">
            <div className="flex items-start gap-4">
              <div style={{ width: "7vh", height: "7vh" }} className={cn("w-16 h-16 rounded-2xl flex items-center justify-center shadow-sm bg-gray-700")}>
                <Layers 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">{famille.intitule}</h1>
                  <StatusBadge status={family.status} />
                </div> */}
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span className="font-mono bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded text-xs">{famille.code}</span>
                  <span>{famille.type_libelle}</span>
                  <span>{articleFiltered.length} articles</span>
                </div>
              </div>
            </div>

            <div className="flex gap-3">
              <button 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="Copy">
                <Copy className="w-5 h-5" />
              </button>
              {/* <button
                onClick={() => setIsEditModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 bg-[#007E45] text-white rounded-xl text-sm font-medium hover:bg-[#007E45] transition-colors shadow-lg shadow-red-900/20"
              >
                <Edit className="w-4 h-4" />
                Modifier
              </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">
              <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 space-y-6">
                <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                  <Info className="w-5 h-5 text-[#007E45]" />
                  Informations générales
                </h3>
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <p className="text-gray-500 mb-1">Code famille</p>
                      <p className="font-mono font-medium">{famille.code}</p>
                    </div>
                    <div>
                      <p className="text-gray-500 mb-1">Catégorie</p>
                      <p className="font-medium">{famille.type_libelle}</p>
                    </div>
                    <div className="col-span-2">
                      <p className="text-gray-500 mb-1">Description</p>
                      <p className="text-gray-900 dark:text-gray-300 leading-relaxed">
                        Cette famille regroupe l'ensemble des produits liés à {famille.intitule.toLowerCase()}.
                        Utilisée pour la classification analytique et le reporting des ventes.
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 space-y-6">
                <h3 className="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                  <Package className="w-5 h-5 text-[#007E45]" />
                  Règles par défaut
                </h3>
                <div className="space-y-4 text-sm">
                  <div className="flex justify-between py-2 border-b border-gray-100 dark:border-gray-800">
                    <span className="text-gray-500">Taux TVA</span>
                    <span className="font-medium">20%</span>
                  </div>
                  <div className="flex justify-between py-2 border-b border-gray-100 dark:border-gray-800">
                    <span className="text-gray-500">Compte Vente</span>
                    <span className="font-mono">707000</span>
                  </div>
                  <div className="flex justify-between py-2 border-b border-gray-100 dark:border-gray-800">
                    <span className="text-gray-500">Compte Achat</span>
                    <span className="font-mono">607000</span>
                  </div>
                  <div className="flex justify-between py-2">
                    <span className="text-gray-500">Unité de stock</span>
                    <span className="font-medium">Pièce (Pcs)</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'articles' && (
            <DataTable
              columns={[
                { key: 'reference', label: 'Référence', sortable: true },
                { key: 'designation', label: 'Designation', sortable: true },
                { key: 'prix_vente', label: 'Prix de vente', sortable: false, render: (v: any) => `${v.toFixed(2)}€` },
                { key: 'stock_reel', label: 'Stock', sortable: false },
                {
                  key: 'est_actif',
                  label: 'Statut',
                  sortable: true,
                  render: (isActive: any) => <StatusBadgetLettre status={isActive ? 'active' : 'inactive'} />
                },
              ]}
              data={articleFiltered}
              onRowClick={(row: Article) => { dispatch(selectArticle(row)), navigate(`/home/articles/${row.reference.replace(/\//g, '')}`) }}
              actions={null}
              status={isLoading}
            />
          )}

          {activeTab === 'timeline' && (
            <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-12 text-center text-gray-500">
              Aucune activité récente.
            </div>
          )}
        </div>
      </div>

      {/* <ProductFamilyFormModal 
        isOpen={isEditModalOpen} 
        onClose={() => setIsEditModalOpen(false)} 
        initialData={family} 
      /> */}
    </>
  );
};

export default ProductFamilyDetailPage;
