'use client';

import { useTranslations } from 'next-intl';
import {
  ShieldCheck,
  CheckCircle,
  DollarSign,
  Truck,
  Users,
  type LucideIcon,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import { KpiCard } from './kpi-card';
import type {
  SQCDMCategory,
  MorningMeetingTopic,
  UpdateTopicDto,
} from '@/types/lean';
import { SQCDM_CATEGORIES } from '@/types/lean';

interface SqcdmColumnProps {
  /** The SQCDM category */
  category: SQCDMCategory;
  /** Topics for this category */
  topics: MorningMeetingTopic[];
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback when a topic is updated */
  onUpdateTopic?: (id: string, dto: UpdateTopicDto) => void;
  /** Loading state for topic updates */
  isUpdating?: boolean;
}

/**
 * Map category to icon component
 */
const CATEGORY_ICONS: Record<SQCDMCategory, LucideIcon> = {
  SAFETY: ShieldCheck,
  QUALITY: CheckCircle,
  COST: DollarSign,
  DELIVERY: Truck,
  MORALE: Users,
};

/**
 * SQCDM Column component displaying KPIs for a specific category
 */
export function SqcdmColumn({
  category,
  topics,
  editable = false,
  onUpdateTopic,
  isUpdating = false,
}: SqcdmColumnProps) {
  const t = useTranslations('lean.morningMeeting.sqcdm');
  const t2 = useTranslations('lean.morningMeeting');
  const categoryMeta = SQCDM_CATEGORIES[category];
  const Icon = CATEGORY_ICONS[category];
  const label = t(categoryMeta.labelKey);

  // Calculate overall status for the column (most severe status wins)
  const overallStatus = topics.reduce<'GREEN' | 'YELLOW' | 'RED' | 'NEUTRAL'>(
    (worst, topic) => {
      if (topic.status === 'RED') return 'RED';
      if (topic.status === 'YELLOW' && worst !== 'RED') return 'YELLOW';
      if (topic.status === 'GREEN' && worst === 'NEUTRAL') return 'GREEN';
      return worst;
    },
    'NEUTRAL'
  );

  const statusIndicatorColors = {
    GREEN: 'bg-green-500',
    YELLOW: 'bg-yellow-500',
    RED: 'bg-red-500',
    NEUTRAL: 'bg-gray-400',
  };

  return (
    <Card className="flex flex-col h-full">
      <CardHeader
        className={cn(
          'pb-2 border-b',
          categoryMeta.bgColor,
          'rounded-t-xl'
        )}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Icon className={cn('h-5 w-5', categoryMeta.color)} />
            <CardTitle className={cn('text-base', categoryMeta.color)}>
              {label}
            </CardTitle>
          </div>
          <div
            className={cn(
              'h-3 w-3 rounded-full shadow-sm',
              statusIndicatorColors[overallStatus]
            )}
            title={`Status: ${overallStatus}`}
          />
        </div>
        <div className="text-xs text-muted-foreground">
          {topics.length} KPI{topics.length !== 1 ? 's' : ''}
        </div>
      </CardHeader>

      <CardContent className="flex-1 p-0">
        <ScrollArea className="h-[calc(100%-1rem)]">
          <div className="p-3 space-y-2">
            {topics.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                {t2('kpi.noKpis')}
              </p>
            ) : (
              topics
                .sort((a, b) => a.sortOrder - b.sortOrder)
                .map((topic) => (
                  <div key={topic.id} className="group">
                    <KpiCard
                      topic={topic}
                      editable={editable}
                      onUpdate={onUpdateTopic}
                      isUpdating={isUpdating}
                    />
                  </div>
                ))
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
