'use client';

import { useState } from 'react';
import { TrendingUp, TrendingDown, Minus, Pencil, Check, X } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import type { MorningMeetingTopic, KPIStatus, Trend, UpdateTopicDto } from '@/types/lean';
import { KPI_STATUS_COLORS } from '@/types/lean';

interface KpiCardProps {
  /** The topic/KPI data */
  topic: MorningMeetingTopic;
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback when topic is updated */
  onUpdate?: (id: string, dto: UpdateTopicDto) => void;
  /** Loading state for update */
  isUpdating?: boolean;
}

/**
 * Render trend icon
 */
function TrendIcon({ trend }: { trend: Trend | null | undefined }) {
  if (!trend) return null;

  switch (trend) {
    case 'UP':
      return <TrendingUp className="h-4 w-4 text-green-600" />;
    case 'DOWN':
      return <TrendingDown className="h-4 w-4 text-red-600" />;
    case 'STABLE':
      return <Minus className="h-4 w-4 text-gray-500" />;
    default:
      return null;
  }
}

/**
 * Traffic light indicator
 */
function StatusLight({ status }: { status: KPIStatus }) {
  const colors = KPI_STATUS_COLORS[status];
  return (
    <div
      className={cn(
        'h-4 w-4 rounded-full border-2 shadow-sm',
        colors.bg,
        colors.border
      )}
      title={status}
    />
  );
}

/**
 * KPI Card component for displaying a single KPI with traffic light status
 */
export function KpiCard({
  topic,
  editable = false,
  onUpdate,
  isUpdating = false,
}: KpiCardProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editedValue, setEditedValue] = useState(topic.value || '');
  const [editedStatus, setEditedStatus] = useState<KPIStatus>(topic.status);
  const [editedTrend, setEditedTrend] = useState<Trend | undefined>(
    topic.trend || undefined
  );

  const handleSave = () => {
    if (onUpdate) {
      onUpdate(topic.id, {
        value: editedValue || undefined,
        status: editedStatus,
        trend: editedTrend,
      });
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditedValue(topic.value || '');
    setEditedStatus(topic.status);
    setEditedTrend(topic.trend || undefined);
    setIsEditing(false);
  };

  const statusColors = KPI_STATUS_COLORS[topic.status];

  if (isEditing && editable) {
    return (
      <Card className={cn('border-l-4', statusColors.border)}>
        <CardContent className="p-3 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium truncate">{topic.title}</span>
            <div className="flex gap-1">
              <Button
                size="icon"
                variant="ghost"
                className="h-6 w-6"
                onClick={handleSave}
                disabled={isUpdating}
              >
                <Check className="h-3 w-3" />
              </Button>
              <Button
                size="icon"
                variant="ghost"
                className="h-6 w-6"
                onClick={handleCancel}
                disabled={isUpdating}
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          </div>

          <div className="flex gap-2">
            <Input
              value={editedValue}
              onChange={(e) => setEditedValue(e.target.value)}
              placeholder="Wert"
              className="h-8 text-sm"
            />
            {topic.unit && (
              <span className="text-sm text-muted-foreground self-center">
                {topic.unit}
              </span>
            )}
          </div>

          <div className="flex gap-2">
            <Select
              value={editedStatus}
              onValueChange={(v) => setEditedStatus(v as KPIStatus)}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="GREEN">Gruen</SelectItem>
                <SelectItem value="YELLOW">Gelb</SelectItem>
                <SelectItem value="RED">Rot</SelectItem>
                <SelectItem value="NEUTRAL">Neutral</SelectItem>
              </SelectContent>
            </Select>

            <Select
              value={editedTrend || 'NONE'}
              onValueChange={(v) =>
                setEditedTrend(v === 'NONE' ? undefined : (v as Trend))
              }
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="NONE">Kein Trend</SelectItem>
                <SelectItem value="UP">Steigend</SelectItem>
                <SelectItem value="DOWN">Fallend</SelectItem>
                <SelectItem value="STABLE">Stabil</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card
      className={cn(
        'border-l-4 transition-colors hover:shadow-sm',
        statusColors.border,
        statusColors.bg
      )}
    >
      <CardContent className="p-3">
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <StatusLight status={topic.status} />
              <span className="text-sm font-medium truncate">{topic.title}</span>
            </div>

            <div className="mt-1 flex items-baseline gap-1">
              <span className={cn('text-lg font-bold', statusColors.text)}>
                {topic.value || '-'}
              </span>
              {topic.unit && (
                <span className="text-xs text-muted-foreground">{topic.unit}</span>
              )}
              {topic.target && (
                <span className="text-xs text-muted-foreground ml-1">
                  / Ziel: {topic.target}
                </span>
              )}
            </div>

            {topic.note && (
              <p className="mt-1 text-xs text-muted-foreground line-clamp-2">
                {topic.note}
              </p>
            )}
          </div>

          <div className="flex items-center gap-1">
            <TrendIcon trend={topic.trend} />
            {editable && (
              <Button
                size="icon"
                variant="ghost"
                className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                onClick={() => setIsEditing(true)}
              >
                <Pencil className="h-3 w-3" />
              </Button>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
