'use client';

import { useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Skeleton } from '@/components/ui/skeleton';
import { Check, User, Calendar } from 'lucide-react';
import { format, type Locale } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { SkillLevelIndicator } from './skill-level-badge';
import {
  type SkillLevelValue,
  SKILL_LEVEL_COLORS,
} from '@/hooks/lean/use-skills';
import type { SkillEntryDetails } from '@/hooks/lean/use-skill-matrix';

interface SkillCellProps {
  /** Skill entry data */
  entry: SkillEntryDetails;
  /** Employee ID for this cell */
  employeeId: string;
  /** Skill ID for this cell */
  skillId: string;
  /** Callback when level is changed */
  onLevelChange?: (employeeId: string, skillId: string, newLevel: SkillLevelValue) => void;
  /** Whether editing is allowed */
  editable?: boolean;
  /** Whether the cell is loading */
  isLoading?: boolean;
  /** Locale for date formatting */
  locale?: string;
}

/**
 * Individual cell in the skill matrix with quick-edit functionality
 */
export function SkillCell({
  entry,
  employeeId,
  skillId,
  onLevelChange,
  editable = true,
  isLoading = false,
  locale = 'de',
}: SkillCellProps) {
  const t = useTranslations('lean.skillMatrix.levels');
  const tCommon = useTranslations('common');
  const [isOpen, setIsOpen] = useState(false);
  const [pendingLevel, setPendingLevel] = useState<SkillLevelValue | null>(null);

  const levels: SkillLevelValue[] = [0, 1, 2, 3, 4];
  const currentLevel = entry.level;
  const colors = SKILL_LEVEL_COLORS[currentLevel];

  const dateLocale = locale === 'de' ? de : enUS;

  const handleLevelSelect = useCallback(
    (newLevel: SkillLevelValue) => {
      if (newLevel === currentLevel) {
        setIsOpen(false);
        return;
      }

      setPendingLevel(newLevel);

      if (onLevelChange) {
        onLevelChange(employeeId, skillId, newLevel);
      }

      setIsOpen(false);
      // Reset pending after a short delay to show optimistic update
      setTimeout(() => setPendingLevel(null), 500);
    },
    [currentLevel, employeeId, skillId, onLevelChange]
  );

  if (isLoading) {
    return (
      <div className="p-2">
        <Skeleton className="w-10 h-10 rounded-full mx-auto" />
      </div>
    );
  }

  const displayLevel = pendingLevel ?? currentLevel;
  const displayColors = SKILL_LEVEL_COLORS[displayLevel];

  const cellContent = (
    <div
      className={cn(
        'w-10 h-10 rounded-full flex items-center justify-center font-semibold text-sm transition-all',
        displayColors.bg,
        displayColors.text,
        editable && 'cursor-pointer hover:ring-2 hover:ring-primary/50',
        pendingLevel !== null && 'animate-pulse'
      )}
    >
      {displayLevel}
    </div>
  );

  // If not editable, just show a tooltip with details
  if (!editable) {
    return (
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger asChild>
            <div className="flex justify-center p-2">{cellContent}</div>
          </TooltipTrigger>
          <TooltipContent>
            <CellTooltipContent entry={entry} t={t} dateLocale={dateLocale} />
          </TooltipContent>
        </Tooltip>
      </TooltipProvider>
    );
  }

  return (
    <Popover open={isOpen} onOpenChange={setIsOpen}>
      <PopoverTrigger asChild>
        <div className="flex justify-center p-2">{cellContent}</div>
      </PopoverTrigger>
      <PopoverContent className="w-64 p-3" align="center">
        <div className="space-y-3">
          {/* Level selector */}
          <div className="grid grid-cols-5 gap-1">
            {levels.map((level) => {
              const levelColors = SKILL_LEVEL_COLORS[level];
              const isSelected = level === currentLevel;

              return (
                <TooltipProvider key={level}>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant="outline"
                        size="sm"
                        className={cn(
                          'w-10 h-10 p-0 relative',
                          levelColors.bg,
                          levelColors.text,
                          levelColors.border,
                          isSelected && 'ring-2 ring-primary'
                        )}
                        onClick={() => handleLevelSelect(level)}
                      >
                        {level}
                        {isSelected && (
                          <Check className="w-3 h-3 absolute -top-1 -right-1 bg-primary text-primary-foreground rounded-full p-0.5" />
                        )}
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent side="top">
                      <p>{t(String(level))}</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              );
            })}
          </div>

          {/* Entry details */}
          {entry.assessedAt && (
            <div className="pt-2 border-t space-y-1 text-xs text-muted-foreground">
              {entry.assessedBy && (
                <div className="flex items-center gap-1">
                  <User className="w-3 h-3" />
                  <span>
                    {entry.assessedBy.firstName} {entry.assessedBy.lastName}
                  </span>
                </div>
              )}
              <div className="flex items-center gap-1">
                <Calendar className="w-3 h-3" />
                <span>
                  {format(new Date(entry.assessedAt), 'dd.MM.yyyy', { locale: dateLocale })}
                </span>
              </div>
              {entry.notes && (
                <p className="text-muted-foreground italic mt-1">{entry.notes}</p>
              )}
            </div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}

/**
 * Tooltip content for cell details
 */
function CellTooltipContent({
  entry,
  t,
  dateLocale,
}: {
  entry: SkillEntryDetails;
  t: (key: string) => string;
  dateLocale: Locale;
}) {
  return (
    <div className="space-y-1">
      <p className="font-medium">Level {entry.level}: {t(String(entry.level))}</p>
      {entry.assessedAt && (
        <>
          {entry.assessedBy && (
            <p className="text-xs">
              {entry.assessedBy.firstName} {entry.assessedBy.lastName}
            </p>
          )}
          <p className="text-xs text-muted-foreground">
            {format(new Date(entry.assessedAt), 'dd.MM.yyyy', { locale: dateLocale })}
          </p>
        </>
      )}
      {entry.notes && (
        <p className="text-xs italic mt-1 max-w-[200px] truncate">{entry.notes}</p>
      )}
    </div>
  );
}
