'use client';

import { useMemo } from 'react';
import { useTranslations } from 'next-intl';
import {
  BarChart as RechartsBarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  ReferenceLine,
  Cell,
} from 'recharts';
import { ChartContainer, ChartEmptyState } from '@/components/charts/chart-container';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import type { SkillGapAnalysis } from '@/hooks/lean/use-skill-matrix';

interface SkillGapChartProps {
  /** Skill gap analysis data */
  data: SkillGapAnalysis[];
  /** Target level for comparison */
  targetLevel?: number;
  /** Whether data is loading */
  isLoading?: boolean;
  /** Chart height */
  height?: number;
  /** Additional CSS classes */
  className?: string;
}

/**
 * Bar chart showing actual vs target skill levels
 * Highlights gaps between current average and target
 */
export function SkillGapChart({
  data,
  targetLevel = 2,
  isLoading = false,
  height = 400,
  className,
}: SkillGapChartProps) {
  const t = useTranslations('lean.skillMatrix');

  // Transform data for the chart
  const chartData = useMemo(() => {
    return data
      .slice(0, 10) // Limit to top 10 gaps
      .map((item) => ({
        name: item.skillName.length > 15 ? item.skillName.slice(0, 12) + '...' : item.skillName,
        fullName: item.skillName,
        actual: item.averageLevel,
        target: item.targetLevel,
        gap: item.gap,
        employeesBelow: item.employeesBelow,
        employeesAtOrAbove: item.employeesAtOrAbove,
        total: item.totalEmployees,
        category: item.category,
      }));
  }, [data]);

  const getBarColor = (gap: number) => {
    if (gap <= 0) return 'hsl(142, 76%, 36%)'; // Green - no gap
    if (gap < 1) return 'hsl(48, 96%, 53%)'; // Yellow - small gap
    return 'hsl(0, 84%, 60%)'; // Red - significant gap
  };

  if (!isLoading && data.length === 0) {
    return (
      <ChartContainer
        title={t('gapAnalysis')}
        description={t('gapAnalysisDescription')}
        height={height}
        className={className}
      >
        <ChartEmptyState message={t('noGapData')} />
      </ChartContainer>
    );
  }

  return (
    <ChartContainer
      title={t('gapAnalysis')}
      description={t('gapAnalysisDescription')}
      isLoading={isLoading}
      height={height}
      className={className}
      headerAction={
        <Badge variant="outline">
          {t('targetLevel')}: {targetLevel}
        </Badge>
      }
    >
      <ResponsiveContainer width="100%" height="100%">
        <RechartsBarChart
          data={chartData}
          layout="vertical"
          margin={{ top: 10, right: 30, left: 80, bottom: 10 }}
        >
          <CartesianGrid
            strokeDasharray="3 3"
            className="stroke-muted"
            opacity={0.5}
            horizontal={true}
            vertical={false}
          />
          <XAxis
            type="number"
            domain={[0, 4]}
            ticks={[0, 1, 2, 3, 4]}
            className="text-xs"
            tick={{ fill: 'hsl(var(--muted-foreground))' }}
          />
          <YAxis
            dataKey="name"
            type="category"
            className="text-xs"
            tick={{ fill: 'hsl(var(--muted-foreground))' }}
            width={75}
          />
          <Tooltip
            content={<CustomTooltip targetLevel={targetLevel} t={t} />}
            cursor={{ fill: 'hsl(var(--muted))', opacity: 0.3 }}
          />
          <Legend
            wrapperStyle={{ paddingTop: '10px' }}
            formatter={(value) => (
              <span className="text-sm text-muted-foreground">
                {value === 'actual' ? t('actualLevel') : t('targetLevel')}
              </span>
            )}
          />

          {/* Target reference line */}
          <ReferenceLine
            x={targetLevel}
            stroke="hsl(var(--primary))"
            strokeDasharray="5 5"
            strokeWidth={2}
          />

          {/* Actual level bars with conditional coloring */}
          <Bar
            dataKey="actual"
            name="actual"
            radius={[0, 4, 4, 0]}
            maxBarSize={30}
          >
            {chartData.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={getBarColor(entry.gap)} />
            ))}
          </Bar>
        </RechartsBarChart>
      </ResponsiveContainer>
    </ChartContainer>
  );
}

/**
 * Custom tooltip component
 */
interface CustomTooltipProps {
  active?: boolean;
  payload?: Array<{
    payload: {
      fullName: string;
      actual: number;
      target: number;
      gap: number;
      employeesBelow: number;
      employeesAtOrAbove: number;
      total: number;
      category: string | null;
    };
  }>;
  targetLevel: number;
  t: (key: string) => string;
}

function CustomTooltip({ active, payload, targetLevel, t }: CustomTooltipProps) {
  if (!active || !payload || !payload.length) {
    return null;
  }

  const data = payload[0].payload;

  return (
    <div className="bg-popover border rounded-lg shadow-lg p-3 text-sm">
      <p className="font-medium mb-2">{data.fullName}</p>
      {data.category && (
        <Badge variant="secondary" className="mb-2 text-xs">
          {data.category}
        </Badge>
      )}
      <div className="space-y-1 text-muted-foreground">
        <div className="flex justify-between gap-4">
          <span>{t('actualLevel')}:</span>
          <span className="font-medium text-foreground">{data.actual.toFixed(2)}</span>
        </div>
        <div className="flex justify-between gap-4">
          <span>{t('targetLevel')}:</span>
          <span className="font-medium text-foreground">{data.target}</span>
        </div>
        <div className="flex justify-between gap-4 pt-1 border-t">
          <span>{t('gap')}:</span>
          <span
            className={cn(
              'font-medium',
              data.gap <= 0 ? 'text-green-600' : data.gap < 1 ? 'text-yellow-600' : 'text-red-600'
            )}
          >
            {data.gap > 0 ? '+' : ''}{data.gap.toFixed(2)}
          </span>
        </div>
        <div className="flex justify-between gap-4">
          <span>{t('belowTarget')}:</span>
          <span className="text-red-600">{data.employeesBelow}</span>
        </div>
        <div className="flex justify-between gap-4">
          <span>{t('atOrAboveTarget')}:</span>
          <span className="text-green-600">{data.employeesAtOrAbove}</span>
        </div>
      </div>
    </div>
  );
}

/**
 * Summary statistics component
 */
interface GapSummaryProps {
  data: SkillGapAnalysis[];
  className?: string;
}

export function SkillGapSummary({ data, className }: GapSummaryProps) {
  const t = useTranslations('lean.skillMatrix');

  const stats = useMemo(() => {
    if (data.length === 0) {
      return { criticalGaps: 0, warningGaps: 0, okSkills: 0, avgGap: 0 };
    }

    let criticalGaps = 0;
    let warningGaps = 0;
    let okSkills = 0;
    let totalGap = 0;

    for (const item of data) {
      totalGap += item.gap;
      if (item.gap > 1) {
        criticalGaps++;
      } else if (item.gap > 0) {
        warningGaps++;
      } else {
        okSkills++;
      }
    }

    return {
      criticalGaps,
      warningGaps,
      okSkills,
      avgGap: totalGap / data.length,
    };
  }, [data]);

  return (
    <div className={cn('grid grid-cols-2 sm:grid-cols-4 gap-4', className)}>
      <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-4 text-center">
        <p className="text-2xl font-bold text-red-600">{stats.criticalGaps}</p>
        <p className="text-xs text-muted-foreground">{t('criticalGaps')}</p>
      </div>
      <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-4 text-center">
        <p className="text-2xl font-bold text-yellow-600">{stats.warningGaps}</p>
        <p className="text-xs text-muted-foreground">{t('warningGaps')}</p>
      </div>
      <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-4 text-center">
        <p className="text-2xl font-bold text-green-600">{stats.okSkills}</p>
        <p className="text-xs text-muted-foreground">{t('noGap')}</p>
      </div>
      <div className="bg-muted rounded-lg p-4 text-center">
        <p className="text-2xl font-bold">{stats.avgGap.toFixed(2)}</p>
        <p className="text-xs text-muted-foreground">{t('averageGap')}</p>
      </div>
    </div>
  );
}
