import React, { useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import { Plus, Eye, Edit, Mail, Phone } from 'lucide-react';
import DataTable from '@/components/DataTable';
import StatusBadgetLettre from '@/components/StatusBadgetLettre';
import { toast } from '@/components/ui/use-toast';
import { Commercial } from '@/types/commercialType';
import { commercialsStatus, getAllcommercials } from '@/store/features/commercial/selectors';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { useNavigate } from 'react-router-dom';
import { getCommercials } from '@/store/features/commercial/thunk';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import AdvancedFilters from '@/components/common/AdvancedFilters';
import ExportDropdown from '@/components/common/ExportDropdown';
import ModalCommercial from '@/components/modal/ModalCommercial';

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

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'numero', label: 'Numéro', visible: true, locked: true },
  { key: 'fullName', label: 'Nom complet', visible: true },
  { key: 'fonction', label: 'Fonction', visible: true },
  { key: 'email', label: 'Email', visible: true },
  { key: 'telephone', label: 'Téléphone', visible: true },
  { key: 'service', label: 'Service', visible: false },
  { key: 'ville', label: 'Ville', visible: false },
  { key: 'roles', label: 'Rôles', visible: true },
  { key: 'est_actif', label: 'Statut', visible: true },
];

const CommercialPage = () => {
  const dispatch = useAppDispatch();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editing, setEditing] = useState<Commercial | null>(null);
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);
  const [activeFilters, setActiveFilters] = useState<Record<string, string[] | undefined>>({});

  const commercials = useAppSelector(getAllcommercials) as Commercial[];
  const statusCommercial = useAppSelector(commercialsStatus);

  console.log("commercials : ",commercials);
  
  const isLoading = statusCommercial === 'loading' && commercials.length === 0;

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

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

  // ============================================
  // FILTRES
  // ============================================

  const filterDefinitions = useMemo(() => [
    {
      key: 'role',
      label: 'Rôle',
      options: [
        { value: 'vendeur', label: 'Vendeur', color: 'bg-blue-400' },
        { value: 'acheteur', label: 'Acheteur', color: 'bg-purple-400' },
        { value: 'caissier', label: 'Caissier', color: 'bg-orange-400' },
        { value: 'chef_ventes', label: 'Chef des ventes', color: 'bg-yellow-400' },
      ],
    },
  ], []);

  // ============================================
  // DONNÉES FILTRÉES
  // ============================================

  const filteredCommercials = useMemo(() => {
    let result = [...commercials];
    // Filtre par rôle
    if (activeFilters.role && activeFilters.role.length > 0) {
      result = result.filter(c => {
        const roles: string[] = [];
        if (c.vendeur) roles.push('vendeur');
        if (c.acheteur) roles.push('acheteur');
        if (c.caissier) roles.push('caissier');
        if (c.chef_ventes) roles.push('chef_ventes');
        return activeFilters.role!.some(r => roles.includes(r));
      });
    }

    return result.sort((a, b) => a.numero - b.numero);
  }, [commercials, activeFilters]);

  // ============================================
  // COLONNES
  // ============================================

  const allColumnsDefinition = useMemo(() => ({
    numero: { 
      key: 'numero', 
      label: 'Numéro', 
      sortable: true,
      render: (value: number) => (
        <span className="font-mono text-sm font-medium text-gray-900 dark:text-white">
          #{value}
        </span>
      ),
    },
    fullName: {
      key: 'fullName',
      label: 'Nom complet',
      sortable: true,
      render: (_: any, row: Commercial) => {
        const initials = `${row.prenom?.charAt(0) || ''}${row.nom?.charAt(0) || ''}`.toUpperCase();
        return (
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-full bg-[#007E45]/10 flex items-center justify-center text-xs font-bold text-[#007E45]">
              {initials || '?'}
            </div>
            <div>
              <p className="text-sm font-medium text-gray-900 dark:text-white">
                {row.prenom} {row.nom}
              </p>
              {row.matricule && (
                <p className="text-xs text-gray-500">Mat: {row.matricule}</p>
              )}
            </div>
          </div>
        );
      },
    },
    fonction: { 
      key: 'fonction', 
      label: 'Fonction', 
      sortable: true,
      render: (value: string) => (
        <span className="text-sm text-gray-700 dark:text-gray-300">
          {value || '-'}
        </span>
      ),
    },
    email: {
      key: 'email',
      label: 'Email',
      sortable: true,
      render: (value: string | null) => value ? (
        <a 
          href={`mailto:${value}`} 
          className="text-sm text-[#007E45] hover:underline flex items-center gap-1"
          onClick={(e) => e.stopPropagation()}
        >
          <Mail className="w-3 h-3" />
          {value}
        </a>
      ) : (
        <span className="text-gray-400">-</span>
      ),
    },
    telephone: {
      key: 'telephone',
      label: 'Téléphone',
      sortable: true,
      render: (value: string, row: Commercial) => {
        const phone = value || row.tel_portable;
        return phone ? (
          <a 
            href={`tel:${phone}`} 
            className="text-sm text-gray-700 dark:text-gray-300 hover:text-[#007E45] flex items-center gap-1"
            onClick={(e) => e.stopPropagation()}
          >
            <Phone className="w-3 h-3" />
            {phone}
          </a>
        ) : (
          <span className="text-gray-400">-</span>
        );
      },
    },
    service: {
      key: 'service',
      label: 'Service',
      sortable: true,
      render: (value: string) => (
        <span className="text-sm text-gray-600 dark:text-gray-400">
          {value || '-'}
        </span>
      ),
    },
    ville: {
      key: 'ville',
      label: 'Ville',
      sortable: true,
      render: (value: string, row: Commercial) => (
        <span className="text-sm text-gray-600 dark:text-gray-400">
          {value ? `${value}${row.code_postal ? ` (${row.code_postal})` : ''}` : '-'}
        </span>
      ),
    },
    roles: {
      key: 'roles',
      label: 'Rôles',
      sortable: false,
      render: (_: any, row: Commercial) => {
        const roles: { label: string; color: string }[] = [];
        if (row.vendeur) roles.push({ label: 'Vendeur', color: 'bg-blue-100 text-blue-700' });
        if (row.acheteur) roles.push({ label: 'Acheteur', color: 'bg-purple-100 text-purple-700' });
        if (row.caissier) roles.push({ label: 'Caissier', color: 'bg-orange-100 text-orange-700' });
        if (row.chef_ventes) roles.push({ label: 'Chef', color: 'bg-yellow-100 text-yellow-700' });

        if (roles.length === 0) return <span className="text-gray-400">-</span>;

        return (
          <div className="flex flex-wrap gap-1">
            {roles.slice(0, 2).map((role, i) => (
              <span 
                key={i} 
                className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${role.color}`}
              >
                {role.label}
              </span>
            ))}
            {roles.length > 2 && (
              <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-600">
                +{roles.length - 2}
              </span>
            )}
          </div>
        );
      },
    },
  }), []);

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

  // ============================================
  // FORMATEURS EXPORT
  // ============================================

  const columnFormatters: Record<string, (value: any, row: Commercial) => string> = {
    fullName: (_, row) => `${row.prenom || ''} ${row.nom || ''}`.trim(),
    roles: (_, row) => {
      const roles: string[] = [];
      if (row.vendeur) roles.push('Vendeur');
      if (row.acheteur) roles.push('Acheteur');
      if (row.caissier) roles.push('Caissier');
      if (row.chef_ventes) roles.push('Chef des ventes');
      return roles.join(', ') || '-';
    },
    est_actif: (value) => value ? 'Actif' : 'Inactif',
    telephone: (value, row) => value || row.tel_portable || '-',
  };

  // ============================================
  // HANDLERS
  // ============================================

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

  const handleEdit = (row: Commercial) => {
    setEditing(row);
    setIsModalOpen(true);
  };

  const actions = (row: Commercial) => (
    <>
      <button
        onClick={(e) => {
          e.stopPropagation();
          // navigate(`/home/commercials/${row.numero}`);
          toast({ title: 'Voir détails', description: `Commercial #${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>
      {row.email && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            window.location.href = `mailto:${row.email}`;
          }}
          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>Commerciaux - Dataven</title>
        <meta name="description" content="Gestion des commerciaux" />
      </Helmet>

      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Commerciaux</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {filteredCommercials.length} commercial{filteredCommercials.length > 1 ? 'x' : ''}
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <ColumnSelector columns={columnConfig} onChange={setColumnConfig} />
            
            <ExportDropdown
              data={filteredCommercials}
              columns={columnConfig}
              columnFormatters={columnFormatters}
              filename="commerciaux"
            />

            <AdvancedFilters
              filters={filterDefinitions}
              activeFilters={activeFilters}
              onFilterChange={(key, values) => {
                setActiveFilters(prev => ({ ...prev, [key]: values }));
              }}
              onReset={() => setActiveFilters({})}
            />

            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouveau commercial
            </PrimaryButton_v2>
          </div>
        </div>

        {/* DataTable */}
        <DataTable
          columns={visibleColumns}
          data={filteredCommercials}
          onRowClick={(row: Commercial) => {
            toast({ title: 'Voir détails', description: `Commercial: ${row.prenom} ${row.nom}` });
          }}
          actions={actions}
          status={isLoading}
          searchLabel="Rechercher par: nom, email, fonction..."
        />
      </div>

      {/* Modal */}
      <ModalCommercial
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        editing={editing}
      />
    </>
  );
};

export default CommercialPage;