'use client';

import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { BarChart3, TrendingUp, TrendingDown, Minus, type LucideIcon } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Skeleton } from '@/components/ui/skeleton';
import { WidgetContainer } from '../widget-container';

export type TrendDirection = 'up' | 'down' | 'neutral';

export interface StatConfig {
  id: string;
  labelKey: string;
  value: string | number;
  previousValue?: string | number;
  trend?: TrendDirection;
  trendText?: string;
  icon?: LucideIcon;
  iconColor?: string;
}

interface StatsWidgetProps {
  id: string;
  title?: string;
  stat: StatConfig;
  isLoading?: boolean;
  isEditing?: boolean;
  onRemove?: () => void;
  className?: string;
}

/**
 * Get trend icon component based on direction
 */
function getTrendIcon(trend: TrendDirection) {
  switch (trend) {
    case 'up':
      return TrendingUp;
    case 'down':
      return TrendingDown;
    default:
      return Minus;
  }
}

/**
 * Get trend color class based on direction
 */
function getTrendColor(trend: TrendDirection): string {
  switch (trend) {
    case 'up':
      return 'text-green-500';
    case 'down':
      return 'text-red-500';
    default:
      return 'text-muted-foreground';
  }
}

/**
 * Stats Widget - Displays a single KPI with optional trend indicator
 */
export function StatsWidget({
  id,
  title,
  stat,
  isLoading = false,
  isEditing = false,
  onRemove,
  className,
}: StatsWidgetProps) {
  const t = useTranslations('widgets.stats');

  const TrendIcon = stat.trend ? getTrendIcon(stat.trend) : null;
  const StatIcon = stat.icon || BarChart3;

  return (
    <WidgetContainer
      id={id}
      title={title || t(stat.labelKey)}
      icon={<StatIcon className={cn('h-4 w-4', stat.iconColor || 'text-primary')} />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      {isLoading ? (
        <div className="space-y-2">
          <Skeleton className="h-8 w-24" />
          <Skeleton className="h-4 w-32" />
        </div>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <div className="text-3xl font-bold tracking-tight tabular-nums">{stat.value}</div>

          {(stat.trend || stat.trendText) && (
            <div className={cn('mt-1 flex items-center gap-1 text-sm', getTrendColor(stat.trend || 'neutral'))}>
              {TrendIcon && <TrendIcon className="h-4 w-4" />}
              <span>{stat.trendText}</span>
            </div>
          )}
        </motion.div>
      )}
    </WidgetContainer>
  );
}

/**
 * Stats Grid - Displays multiple stats in a grid layout
 */
interface StatsGridWidgetProps {
  id: string;
  stats: StatConfig[];
  isLoading?: boolean;
  isEditing?: boolean;
  onRemove?: () => void;
  className?: string;
  columns?: 2 | 3 | 4;
}

export function StatsGridWidget({
  id,
  stats,
  isLoading = false,
  isEditing = false,
  onRemove,
  className,
  columns = 2,
}: StatsGridWidgetProps) {
  const t = useTranslations('widgets.stats');

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<BarChart3 className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
      colSpan={columns > 2 ? 2 : 1}
    >
      <div
        className={cn('grid gap-4', {
          'grid-cols-2': columns === 2,
          'grid-cols-3': columns === 3,
          'grid-cols-4': columns === 4,
        })}
      >
        {isLoading
          ? Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="space-y-2">
                <Skeleton className="h-6 w-20" />
                <Skeleton className="h-4 w-16" />
              </div>
            ))
          : stats.map((stat, index) => {
              const TrendIcon = stat.trend ? getTrendIcon(stat.trend) : null;
              const StatIcon = stat.icon;

              return (
                <motion.div
                  key={stat.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.05 }}
                  className="space-y-1"
                >
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    {StatIcon && <StatIcon className="h-3 w-3" />}
                    <span>{t(stat.labelKey)}</span>
                  </div>
                  <div className="text-2xl font-bold tabular-nums">{stat.value}</div>
                  {(stat.trend || stat.trendText) && (
                    <div
                      className={cn(
                        'flex items-center gap-1 text-xs',
                        getTrendColor(stat.trend || 'neutral')
                      )}
                    >
                      {TrendIcon && <TrendIcon className="h-3 w-3" />}
                      <span>{stat.trendText}</span>
                    </div>
                  )}
                </motion.div>
              );
            })}
      </div>
    </WidgetContainer>
  );
}
