import { useState, useMemo, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { Plus, Eye, Edit, Trash2, MoreVertical, Package, Copy, Euro, Box, AlertTriangle, Percent } from 'lucide-react';
import DataTable from '@/components/DataTable';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { articleStatus, getAllArticles } from '@/store/features/article/selectors';
import { getArticles } from '@/store/features/article/thunk';
import { selectArticle } from '@/store/features/article/slice';
import { Article } from '@/types/articleType';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import { filterItemByPeriod, hasSpecialChars } from '@/components/filter/ItemsFilter';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { ModalArticle } from '@/components/modal/ModalArticle';
import StatusBadgetLettre from '@/components/StatusBadgetLettre';
import { familleStatus } from '@/store/features/famille/selectors';
import { getfamilles } from '@/store/features/famille/thunk';
import { FAMILLE_COLORS } from './ProductFamiliesPage';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import PeriodSelector from '@/components/common/PeriodSelector';
import { useDashboardData } from '@/store/hooks/useAppData';

// ============================================
// CONFIGURATION DES COLONNES
// ============================================

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'reference', label: 'Référence', visible: true, locked: true },
  { key: 'designation', label: 'Désignation', visible: true },
  { key: 'famille_code', label: 'Famille', visible: true },
  { key: 'prix_vente', label: 'Prix de vente', visible: true },
  { key: 'stock_reel', label: 'Stock', visible: true },
  { key: 'est_actif', label: 'Statut', visible: true },
];

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

  // État des colonnes visibles
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);

  const articles = useAppSelector(getAllArticles) as Article[];
  
  const statusArticle = useAppSelector(articleStatus);
  const statusFamille = useAppSelector(familleStatus);

  const { refresh  } = useDashboardData();

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

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

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

  const filteredArticles = useMemo(() => {
    return [
      ...filterItemByPeriod(
        articles
          .map(article => ({
            ...article,
            date_creation: article.date_creation ?? undefined,
          }))
          .filter(article => !hasSpecialChars(article.reference ?? '')),
        period,
        'date_creation'
      ),
    ].sort((a, b) => b.stock_reel - a.stock_reel);
  }, [articles, period]);

  const kpis = useMemo(() => {
    const total = filteredArticles.length;

    const actifs = filteredArticles.filter(a => a.est_actif !== false);
    const inactifs = filteredArticles.filter(a => a.est_actif === false);

    const stockTotal = filteredArticles.reduce((sum, a) => sum + (a.stock_reel || 0), 0);
    const stockDisponible = filteredArticles.reduce((sum, a) => sum + (a.stock_disponible || a.stock_reel || 0), 0);
    const stockReserve = filteredArticles.reduce((sum, a) => sum + (a.stock_reserve || 0), 0);

    const stockBas = filteredArticles.filter(a => a.stock_mini && a.stock_reel < a.stock_mini);
    const rupture = filteredArticles.filter(a => a.stock_reel <= 0);

    const valeurStockAchat = filteredArticles.reduce((sum, a) => sum + (a.prix_achat || a.prix_revient || 0) * (a.stock_reel || 0), 0);
    const valeurStockVente = filteredArticles.reduce((sum, a) => sum + (a.prix_vente || 0) * (a.stock_reel || 0), 0);

    const prixVenteMoyen = total > 0 ? filteredArticles.reduce((sum, a) => sum + (a.prix_vente || 0), 0) / total : 0;

    const articlesAvecMarge = filteredArticles.filter(a => a.prix_vente && a.prix_achat && a.prix_vente > 0);
    const margeMoyenne =
      articlesAvecMarge.length > 0
        ? articlesAvecMarge.reduce((sum, a) => {
            const marge = ((a.prix_vente - (a.prix_achat || 0)) / a.prix_vente) * 100;
            return sum + marge;
          }, 0) / articlesAvecMarge.length
        : 0;

    return [
      {
        title: 'Total Articles',
        value: total,
        change: `${actifs.length} actifs`,
        trend: 'up' as const,
        icon: Package,
        subtitle: `${inactifs.length} inactif${inactifs.length > 1 ? 's' : ''}`,
        color: 'blue',
      },
      {
        title: 'Valeur Stock',
        value: `${(valeurStockVente / 1000).toFixed(1)}K€`,
        change: `PV`,
        trend: 'up' as const,
        icon: Euro,
        subtitle: `${(valeurStockAchat / 1000).toFixed(1)}K€ (PA)`,
        color: 'green',
      },
      {
        title: 'Stock Total',
        value: stockTotal.toLocaleString('fr-FR'),
        change: `${stockDisponible.toLocaleString()} dispo`,
        trend: 'up' as const,
        icon: Box,
        subtitle: `${stockReserve} réservé${stockReserve > 1 ? 's' : ''}`,
        color: 'purple',
      },
      {
        title: 'Alertes Stock',
        value: stockBas.length + rupture.length,
        change: `${rupture.length} rupture${rupture.length > 1 ? 's' : ''}`,
        trend: stockBas.length + rupture.length > 0 ? ('down' as const) : ('up' as const),
        icon: AlertTriangle,
        subtitle: `${stockBas.length} stock${stockBas.length > 1 ? 's' : ''} bas`,
        color: 'red',
      },
      {
        title: 'Marge Moyenne',
        value: `${margeMoyenne.toFixed(1)}%`,
        change: articlesAvecMarge.length > 0 ? `sur ${articlesAvecMarge.length} art.` : '',
        trend: margeMoyenne >= 30 ? ('up' as const) : ('down' as const),
        icon: Percent,
        subtitle: `Prix moyen: ${prixVenteMoyen.toFixed(0)}€`,
        color: 'teal',
      },
    ];
  }, [filteredArticles]);

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

  const handleEdit = (article: Article) => {
    dispatch(selectArticle(article));
    setEditing(article);
    setIsModalOpen(true);
  };

  const getFamilleColor = (familleCode: string) => {
    if (!familleCode) return FAMILLE_COLORS[0];
    const hash = familleCode.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return FAMILLE_COLORS[hash % FAMILLE_COLORS.length];
  };

  // ============================================
  // COLONNES DYNAMIQUES
  // ============================================

  const allColumnsDefinition = useMemo(() => {
    return {
      reference: { key: 'reference', label: 'Référence', sortable: true },
      designation: { key: 'designation', label: 'Désignation', sortable: true },
      famille_code: {
        key: 'famille_code',
        label: 'Famille',
        sortable: true,
        render: (familleCode: string) => {
          const color = getFamilleColor(familleCode);
          return (
            <span
              style={{
                borderRadius: '20px',
                backgroundColor: `${color}20`,
                color: color,
                padding: '4px 8px',
                fontSize: '12px',
                fontWeight: 500,
              }}
            >
              {familleCode}
            </span>
          );
        },
      },
      prix_vente: {
        key: 'prix_vente',
        label: 'Prix de vente',
        sortable: true,
        render: (v: any) => `${v?.toFixed(2) || '0.00'}€`,
      },
      stock_reel: { key: 'stock_reel', label: 'Stock', sortable: true },
      est_actif: {
        key: 'est_actif',
        label: 'Statut',
        sortable: true,
        render: (isActive: any) => <StatusBadgetLettre status={isActive ? 'actif' : 'inactif'} />,
      },
    };
  }, []);

  const visibleColumns = useMemo(() => {
    return columnConfig
      .filter(col => col.visible)
      .map(col => allColumnsDefinition[col.key as keyof typeof allColumnsDefinition])
      .filter(Boolean);
  }, [columnConfig, allColumnsDefinition]);

  const actions = (row: Article) => (
    <>
      <button
        onClick={() => {
          dispatch(selectArticle(row));
          navigate(`/home/articles/${row.reference.replace(/\//g, '')}`);
        }}
        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={() => 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-gray-50 dark:hover:bg-gray-900 rounded-lg flex items-center gap-2">
            <Copy className="w-4 h-4" /> Dupliquer
          </button>
          <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" /> Désactiver
          </button>
        </div>
      </div>
    </>
  );

  return (
    <>
      <Helmet>
        <title>Articles - Dataven</title>
      </Helmet>

      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} loading={statusArticle} onRefresh={refresh} />

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Catalogue Articles</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{filteredArticles.length} articles référencés</p>
            </div>
            <PeriodSelector value={period} onChange={setPeriod} />
          </div>
          <div className="flex gap-3">
            <ColumnSelector columns={columnConfig} onChange={setColumnConfig} />
            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouvel article
            </PrimaryButton_v2>
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredArticles}
          onRowClick={(row: Article) => {
            dispatch(selectArticle(row));
            navigate(`/home/articles/${row.reference.replace(/\//g, '')}`);
          }}
          actions={actions}
          status={isLoading}
        />
      </div>

      <ModalArticle
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={editing ? `Mettre à jour l'article ${editing.reference}` : 'Nouvel article'}
        editing={editing}
      />
    </>
  );
};

export default ArticlesPage;