import DataTable from '@/components/DataTable';
import { filterItemByPeriod } from '@/components/filter/ItemsFilter';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import { ModalFournisseur } from '@/components/modal/ModalFournisseur';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import StatusBadgetLettre from '@/components/StatusBadgetLettre';
import { toast } from '@/components/ui/use-toast';
import { CompanyInfo } from '@/data/mockData';
import { fournisseurStatus, getAllfournisseurs } from '@/store/features/fournisseur/selectors';
import { selectfournisseur } from '@/store/features/fournisseur/slice';
import { getFournisseurs } from '@/store/features/fournisseur/thunk';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { Fournisseur } from '@/types/fournisseurType';
import { CheckCircle, Edit, Eye, Mail, MapPin, Phone, Plus, Users } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import PeriodSelector from '@/components/common/PeriodSelector';
import { Contacts } from '@/types/clientType';
import { Commercial } from '@/types/commercialType';
import { useDashboardData } from '@/store/hooks/useAppData';

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

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'numero', label: 'Numéro', visible: true, locked: true },
  { key: 'intitule', label: 'Nom', visible: true },
  { key: 'email', label: 'Email', visible: true },
  { key: 'telephone', label: 'Téléphone', visible: true },
  { key: 'contacts', label: 'Contacts', visible: true },
  { key: 'est_actif', label: 'Statut', visible: true },
    { key: 'commercial', label: 'Commercial', visible: true },
];

const SuppliersPage = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [period, setPeriod] = useState<PeriodType>('all');

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

  const fournisseurs = useAppSelector(getAllfournisseurs) as Fournisseur[];
  const statusFournisseur = useAppSelector(fournisseurStatus);
  const [editing, setEditing] = useState<Fournisseur | null>(null);

  const isLoading = statusFournisseur === 'loading' && fournisseurs.length === 0;

  const { refresh  } = useDashboardData();

  useEffect(() => {
    const load = async () => {
      if (statusFournisseur === 'idle' || statusFournisseur === 'failed') await dispatch(getFournisseurs()).unwrap();
    };
    load();
  }, [statusFournisseur, dispatch]);

  const filteredFournisseur = useMemo(() => {
    return [...filterItemByPeriod(fournisseurs, period, 'date_creation')].sort(
      (a, b) => new Date(b.date_creation!).getTime() - new Date(a.date_creation!).getTime()
    );
  }, [fournisseurs, period]);

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

    const withEmail = filteredFournisseur.filter(f => f.email && f.email.trim() !== '').length;
    const withPhone = filteredFournisseur.filter(f => f.telephone && f.telephone.trim() !== '').length;
    const withAddress = filteredFournisseur.filter(
      f => f.adresse && f.code_postal && f.ville && f.adresse.trim() !== '' && f.code_postal.trim() !== '' && f.ville.trim() !== ''
    ).length;

    const completeProfile = filteredFournisseur.filter(
      f =>
        f.intitule &&
        f.adresse &&
        f.code_postal &&
        f.ville &&
        f.email &&
        f.telephone &&
        f.adresse.trim() !== '' &&
        f.email.trim() !== '' &&
        f.telephone.trim() !== ''
    ).length;

    const completionRate = total > 0 ? ((completeProfile / total) * 100).toFixed(1) : '0';
    const emailRate = total > 0 ? ((withEmail / total) * 100).toFixed(1) : '0';
    const phoneRate = total > 0 ? ((withPhone / total) * 100).toFixed(1) : '0';
    const addressRate = total > 0 ? ((withAddress / total) * 100).toFixed(1) : '0';

    return [
      {
        title: 'Total Fournisseurs',
        value: total,
        change: `${completeProfile} complets`,
        trend: 'neutral',
        icon: Users,
        subtitle: `${completionRate}% profils complets`,
      },
      {
        title: 'Avec Email',
        value: withEmail,
        change: `${emailRate}%`,
        trend: withEmail >= total * 0.7 ? 'up' : 'down',
        icon: Mail,
        subtitle: `${total - withEmail} sans email`,
      },
      {
        title: 'Avec Téléphone',
        value: withPhone,
        change: `${phoneRate}%`,
        trend: withPhone >= total * 0.7 ? 'up' : 'down',
        icon: Phone,
        subtitle: `${total - withPhone} sans téléphone`,
      },
      {
        title: 'Avec Adresse',
        value: withAddress,
        change: `${addressRate}%`,
        trend: withAddress >= total * 0.7 ? 'up' : 'down',
        icon: MapPin,
        subtitle: `${total - withAddress} adresse incomplète`,
      },
      {
        title: 'Profils Complets',
        value: completeProfile,
        change: `${completionRate}%`,
        trend: completeProfile >= total * 0.5 ? 'up' : 'down',
        icon: CheckCircle,
        subtitle: `${total - completeProfile} incomplets`,
      },
    ];
  }, [filteredFournisseur, fournisseurs]);

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

  const handleEdit = (row: Fournisseur) => {
    setEditing(row);
    setIsCreateModalOpen(true);
  };

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

  const allColumnsDefinition = useMemo(() => {
    return {
      numero: { key: 'numero', label: 'Numéro', sortable: true },
      intitule: { key: 'intitule', label: 'Nom', sortable: true },
      email: { key: 'email', label: 'Email', sortable: true },
      telephone: { key: 'telephone', label: 'Téléphone', sortable: true,  render: (value: any) => <span>+ {value} </span>, },
      contacts: {
        key: 'contacts',
        label: 'Contacts',
        sortable: false,
        render: (row: Contacts[]) => {

          const count = row?.length || 0;
          const defaultContact = row.find(c => c.est_defaut);

          return (
            <div className="flex flex-col">
              <span className="text-sm font-medium text-gray-900 dark:text-white">
                  {count} contact{count !== 1 ? 's' : ''}
              </span>
              {defaultContact && (
                <span className="text-xs text-gray-500">
                    {defaultContact.nom} {defaultContact.prenom} (défaut)
                </span>
              )}
            </div>
        );
        },
      },
      est_actif: {
        key: 'est_actif',
        label: 'Statut',
        sortable: true,
        render: (isActive: any) => <StatusBadgetLettre status={isActive ? 'actif' : 'inactif'} />,
      },
      commercial: { 
        key: 'commercial', 
        label: 'Commercial', 
        sortable: true,  
        render: (value?: Commercial) => (
          <span>{value?.prenom && value?.nom ? `${value.prenom} ${value.nom}` : '_'}</span>
        )
      },
    };
  }, []);

  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: Fournisseur) => (
    <>
      <button
        onClick={e => {
          e.stopPropagation();
          dispatch(selectfournisseur(row));
          navigate(`/home/fournisseurs/${row.numero}`);
        }}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="Voir détails"
      >
        <Eye className="w-4 h-4" />
      </button>
      <button
        onClick={e => {
          e.stopPropagation();
          handleEdit(row);
        }}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="Modifier"
      >
        <Edit className="w-4 h-4" />
      </button>
      <button
        onClick={e => {
          e.stopPropagation();
          if (row.email) {
            toast({ title: 'Email envoyé', description: `À: ${row.email}` });
          } else {
            toast({ title: "Pas d'email", description: "Ce fournisseur n'a pas d'adresse email", variant: 'destructive' });
          }
        }}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="Envoyer email"
      >
        <Mail className="w-4 h-4" />
      </button>
    </>
  );

  return (
    <>
      <Helmet>
        <title>Fournisseurs - {CompanyInfo.name}</title>
        <meta name="description" content="Gestion de vos fournisseurs" />
      </Helmet>
      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} loading={statusFournisseur} 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">Fournisseurs</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{filteredFournisseur.length} fournisseurs</p>
            </div>
            <PeriodSelector value={period} onChange={setPeriod} />
          </div>
          <div className="flex gap-3">
            <ColumnSelector columns={columnConfig} onChange={setColumnConfig} />
            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouveau fournisseur
            </PrimaryButton_v2>
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredFournisseur}
          onRowClick={(row: Fournisseur) => {
            dispatch(selectfournisseur(row));
            navigate(`/home/fournisseurs/${row.numero}`);
          }}
          actions={actions}
          status={isLoading}
        />
      </div>

      <ModalFournisseur
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        title={editing ? `Mettre à jour le fournisseur ${editing.numero}` : 'Créer un fournisseur'}
        editing={editing}
      />
    </>
  );
};

export default SuppliersPage;