import React from 'react';
import { motion } from 'framer-motion';
import { RefreshCw } from 'lucide-react';
import KpiCard from '@/components/KpiCard';
import PeriodFilter from '@/components/PeriodFilter';

export type PeriodType = 'all' | 'today' | 'week' | 'month' | 'quarter' | 'year' | CustomPeriod;

export interface CustomPeriod {
  id: 'custom';
  start: string;
  end: string;
}

interface KPIBarProps {
  kpis: any;
  period?: PeriodType;
  onPeriodChange?: (period: PeriodType) => void;
  loading?: 'idle' | 'loading' | 'succeeded' | 'failed';
  onRefresh?: () => void | Promise<void>;
}

const KPIBar: React.FC<KPIBarProps> = ({ 
  kpis, 
  period, 
  onPeriodChange, 
  loading = 'idle',
  onRefresh 
}) => {
  const [isRefreshing, setIsRefreshing] = React.useState(false);

  const handleRefresh = async () => {
    if (!onRefresh || isRefreshing) return;
    
    setIsRefreshing(true);
    try {
      await onRefresh();
    } catch (error) {
      console.error('Erreur lors du rafraîchissement:', error);
    } finally {
      setIsRefreshing(false);
    }
  };

  const isLoading = loading === 'idle' || loading === 'loading';
  const showRefreshButton = !isLoading && onRefresh;

  return (
    <div className="mb-6">
      <div style={{ 
        display: 'flex', 
        flexDirection: 'row', 
        justifyContent: 'space-between', 
        alignItems: 'flex-end',
        gap: '16px',
        marginBottom: '16px',
      }}>
        {/* Period Filter */}
        {onPeriodChange && (
          <div className="">
            <PeriodFilter value={period || 'month'} onChange={onPeriodChange} />
          </div>
        )}
        
        {/* Loading State */}
        {isLoading && (
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="sm:w-auto flex items-center justify-center gap-2 px-4 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed sm:order-2"
          >
            <RefreshCw 
              className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} 
            />
          </motion.button>
        )}
        
        {/* Refresh Button */}
        {showRefreshButton && (
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="sm:w-auto flex items-center justify-center gap-2 px-4 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed sm:order-2"
          >
            <RefreshCw 
              className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} 
            />
          </motion.button>
        )}
      </div>
      
      {/* KPI Cards */}
       <div style={{ 
        display: 'flex', 
        overflowX: 'auto', 
        paddingBottom: '16px', 
        gap: '16px',
        scrollSnapType: 'x mandatory',
        scrollbarWidth: 'none', /* Firefox */
        msOverflowStyle: 'none', /* IE et Edge */
        WebkitOverflowScrolling: 'touch'
      }}>
        <style dangerouslySetInnerHTML={{
          __html: `
            @keyframes spin {
              from { transform: rotate(0deg); }
              to { transform: rotate(360deg); }
            }
            div::-webkit-scrollbar {
              display: none;
            }
            @media (min-width: 640px) {
              .kpi-container {
                display: grid !important;
                grid-template-columns: repeat(2, 1fr) !important;
                overflow-x: visible !important;
                padding-bottom: 0 !important;
              }
            }
            @media (min-width: 1024px) {
              .kpi-container {
                grid-template-columns: repeat(4, 1fr) !important;
              }
            }
            @media (min-width: 1280px) {
              .kpi-container {
                grid-template-columns: repeat(5, 1fr) !important;
              }
            }
          `
        }} />
        {kpis.map((kpi: any, index: number) => (
          <div 
            key={index} 
            style={{ 
              minWidth: '260px',
              scrollSnapAlign: 'start'
            }}
          >
            <KpiCard {...kpi} />
          </div>
        ))}
      </div>
    </div>
  );
};

export default KPIBar;


