
import { useState, useMemo, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { Plus, Eye, Trash2, MoreVertical, Layers, Package, CheckCircle, Tag } from 'lucide-react';
import DataTable from '@/components/DataTable';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import { mockProductFamilies, calculateKPIs } from '@/data/mockData';
import { cn } from '@/lib/utils';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { familleStatus, getAllfamilles } from '@/store/features/famille/selectors';
import { Famille } from '@/types/familleType';
import { getfamilles } from '@/store/features/famille/thunk';
import { selectfamille } from '@/store/features/famille/slice';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { ModalFamille } from '@/components/modal/ModalFamille';
import { articleStatus, getAllArticles } from '@/store/features/article/selectors';
import { Article } from '@/types/articleType';
import { getArticles } from '@/store/features/article/thunk';


export const FAMILLE_COLORS = [
  '#3B82F6', // blue
  '#10B981', // green
  '#8B5CF6', // purple
  '#EC4899', // pink
  '#F59E0B', // yellow
  '#EF4444', // red
  '#6366F1', // indigo
  '#F97316', // orange
  '#14B8A6', // teal
  '#06B6D4', // cyan
  '#10B981', // emerald
  '#84CC16', // lime
  '#F59E0B', // amber
  '#F43F5E', // rose
  '#8B5CF6', // violet
  '#D946EF', // fuchsia
  '#0EA5E9', // sky
];


const ProductFamiliesPage = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch()
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [period, setPeriod] = useState<PeriodType>('all');
  const [editing, setEditing] = useState<Famille | null>(null);

  const articles = useAppSelector(getAllArticles) as Article[];
  const statusArticle = useAppSelector(articleStatus)
  const familles = useAppSelector(getAllfamilles) as Famille[];

  const statusFamille = useAppSelector(familleStatus)

  const handleRefresh = async () => {
    await dispatch(getfamilles()).unwrap();
  };

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


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

  // KPI Logic
  const kpis = useMemo(() => {
    const stats = calculateKPIs(mockProductFamilies, period, { dateField: 'createdAt', amountField: 'articleCount' });
    const active = mockProductFamilies.filter(f => f.status === 'active');

    return [
      { title: 'Total Familles', value: mockProductFamilies.length, change: '+1', trend: 'up', icon: Layers },
      { title: 'Familles Actives', value: active.length, change: '', trend: 'neutral', icon: CheckCircle },
      { title: 'Articles / Famille', value: Math.round(stats.totalAmount / (mockProductFamilies.length || 1)), change: '+2', trend: 'up', icon: Package },
      { title: 'Catégories', value: '4', change: '', trend: 'neutral', icon: Tag },
    ];
  }, [period]);

  const handleCreate = () => {
    setEditing(null)
    setIsModalOpen(true);
  };

  const handleEdit = (famille: Famille) => {
    dispatch(selectfamille(famille))
    setEditing(famille)
    setIsModalOpen(true);
  };

  const articleCountByFamille = useMemo(() => {
    return articles.reduce<Record<string, number>>((acc, article) => {
      const familleCode = article.famille_code;
      if (typeof familleCode === 'string' && familleCode.length > 0) {
        acc[familleCode] = (acc[familleCode] || 0) + 1;
      }
      return acc;
    }, {});
  }, [articles]);

  const famillesWithCount = useMemo(() => {
    return familles.map((famille, index) => ({
      ...famille,
      nb_articles: articleCountByFamille[famille?.code] || 0,
      color: FAMILLE_COLORS[index % FAMILLE_COLORS.length] // ✅ Ajouter la couleur ici
    }));
  }, [familles, articleCountByFamille]);


  const columns = useMemo(() => {
    return [
      { key: 'code', label: 'Code', sortable: true },
      { 
        key: 'intitule', 
        label: 'Intitulé', 
        sortable: true,
        render: (value: string, row: Famille & { color: string }) => {
          return (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span 
                style={{ 
                  width: '12px', 
                  height: '12px', 
                  borderRadius: '50%',
                  backgroundColor: row.color, 
                  flexShrink: 0
                }} 
              />
              <span style={{ fontWeight: 500 }}>{value}</span>
            </div>
          );
        } 
      },
      { 
        key: 'code', 
        label: 'Articles', 
        sortable: true,
        render: (code: string) => {
          const nbrArticle = articles.filter(article => article.famille_code === code).length;
          return (
            <span className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded-md text-xs font-medium">
              {nbrArticle}
            </span>
          );
        }
      },
      { key: 'type_libelle', label: 'Type', sortable: false },
    ];
  }, [articleCountByFamille]);

  const actions = (row: any) => (
    <>
      <button
        onClick={(e) => {
          dispatch(selectfamille(row))
          navigate(`/home/familles-articles/${row.code}`)
        }}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors text-gray-600 dark:text-gray-400"
        title="Voir"
      >
        <Eye className="w-4 h-4" />
      </button>
      {/* <button
        onClick={(e) => handleEdit(row)}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors text-gray-600 dark:text-gray-400"
        title="Modifier"
      >
        <Edit className="w-4 h-4" />
      </button> */}
      <div className="relative group">
        <button className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors text-gray-600 dark:text-gray-400"  title="Menu">
          <MoreVertical className="w-4 h-4" />
        </button>
        <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-950 rounded-xl shadow-xl border border-gray-200 dark:border-gray-800 hidden group-hover:block z-10 p-1">
          <button className="w-full text-left px-3 py-2 text-sm hover:bg-red-50 dark:hover:bg-red-900/20 text-red-600 rounded-lg flex items-center gap-2">
            <Trash2 className="w-4 h-4" /> Supprimer
          </button>
        </div>
      </div>
    </>
  );

  return (
    <>
      <Helmet>
        <title>Familles d'articles - Bijou ERP</title>
      </Helmet>

      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} onPeriodChange={setPeriod} loading={statusFamille} onRefresh={handleRefresh} />

        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Familles d'articles</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">Gérez la classification de vos produits</p>
          </div>
          <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
            Nouvelle famille
          </PrimaryButton_v2>
        </div>

        <DataTable
          columns={columns}
          data={famillesWithCount}
          onRowClick={(row: Famille) => {
            dispatch(selectfamille(row))
            navigate(`/home/familles-articles/${row.code}`)
          }}
          actions={actions}
          status={isLoading}
        />
      </div>

      <ModalFamille
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={editing ? `Mettre à jour la famille d'article ${editing.code}` : "Nouvelle famille d'article"}
        editing={editing}
      />
    </>
  );
};

export default ProductFamiliesPage;
