'use client';

import { useMemo, useCallback, useState } from 'react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Search, Filter, Users, ChevronRight } from 'lucide-react';
import { SkillCell } from './skill-cell';
import { SkillLevelLegend } from './skill-level-badge';
import type { SkillLevelValue } from '@/hooks/lean/use-skills';
import type {
  SkillMatrix,
  SkillMatrixSkill,
  SkillMatrixRow,
  SkillEntryDetails,
} from '@/hooks/lean/use-skill-matrix';

interface SkillMatrixGridProps {
  /** Skill matrix data */
  matrix: SkillMatrix;
  /** Whether the matrix is loading */
  isLoading?: boolean;
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback when a skill level is changed */
  onLevelChange?: (employeeId: string, skillId: string, newLevel: SkillLevelValue) => void;
  /** Locale for formatting */
  locale?: string;
  /** Additional CSS classes */
  className?: string;
}

/**
 * Main skill matrix grid component
 * Displays employees (rows) x skills (columns) with inline editing
 */
export function SkillMatrixGrid({
  matrix,
  isLoading = false,
  editable = true,
  onLevelChange,
  locale = 'de',
  className,
}: SkillMatrixGridProps) {
  const t = useTranslations('lean');
  const tCommon = useTranslations('common');
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string | null>(null);

  // Group skills by category
  const skillsByCategory = useMemo(() => {
    const grouped: Record<string, SkillMatrixSkill[]> = {};
    for (const skill of matrix.skills) {
      const category = skill.category || 'other';
      if (!grouped[category]) {
        grouped[category] = [];
      }
      grouped[category].push(skill);
    }
    return grouped;
  }, [matrix.skills]);

  const categories = useMemo(() => Object.keys(skillsByCategory).sort(), [skillsByCategory]);

  // Filter skills by category
  const filteredSkills = useMemo(() => {
    if (!categoryFilter) return matrix.skills;
    return matrix.skills.filter((s) => (s.category || 'other') === categoryFilter);
  }, [matrix.skills, categoryFilter]);

  // Filter employees by search query
  const filteredRows = useMemo(() => {
    if (!searchQuery.trim()) return matrix.matrix;
    const query = searchQuery.toLowerCase();
    return matrix.matrix.filter((row) => {
      const fullName = `${row.employee.user.firstName} ${row.employee.user.lastName}`.toLowerCase();
      const email = row.employee.user.email.toLowerCase();
      const position = row.employee.position?.toLowerCase() || '';
      return fullName.includes(query) || email.includes(query) || position.includes(query);
    });
  }, [matrix.matrix, searchQuery]);

  if (isLoading) {
    return <SkillMatrixSkeleton />;
  }

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className={cn('space-y-4', className)}
    >
      {/* Header with filters and legend */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Users className="h-5 w-5" />
                {matrix.department.name}
              </CardTitle>
              <CardDescription>
                {filteredRows.length} {t('skillMatrix.employees')} | {filteredSkills.length}{' '}
                {t('skills')}
              </CardDescription>
            </div>

            {/* Search and filter */}
            <div className="flex flex-col sm:flex-row gap-2">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder={`${tCommon('search')}...`}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 w-full sm:w-[200px]"
                />
              </div>

              {/* Category filter badges */}
              <div className="flex flex-wrap gap-1">
                <Badge
                  variant={categoryFilter === null ? 'default' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setCategoryFilter(null)}
                >
                  {tCommon('all')}
                </Badge>
                {categories.map((category) => (
                  <Badge
                    key={category}
                    variant={categoryFilter === category ? 'default' : 'outline'}
                    className="cursor-pointer capitalize"
                    onClick={() => setCategoryFilter(category)}
                  >
                    {category}
                  </Badge>
                ))}
              </div>
            </div>
          </div>
        </CardHeader>

        <CardContent className="pb-3">
          <SkillLevelLegend />
        </CardContent>
      </Card>

      {/* Matrix Grid */}
      <Card>
        <ScrollArea className="w-full">
          <div className="min-w-[600px]">
            <table className="w-full border-collapse">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="sticky left-0 z-10 bg-muted/50 p-3 text-left font-medium min-w-[200px]">
                    {t('skillMatrix.employee')}
                  </th>
                  {filteredSkills.map((skill) => (
                    <th key={skill.id} className="p-2 text-center min-w-[60px]">
                      <SkillColumnHeader skill={skill} />
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filteredRows.length === 0 ? (
                  <tr>
                    <td
                      colSpan={filteredSkills.length + 1}
                      className="p-8 text-center text-muted-foreground"
                    >
                      {t('skillMatrix.noEmployeesFound')}
                    </td>
                  </tr>
                ) : (
                  filteredRows.map((row, index) => (
                    <SkillMatrixRowComponent
                      key={row.employee.id}
                      row={row}
                      skills={filteredSkills}
                      editable={editable}
                      onLevelChange={onLevelChange}
                      locale={locale}
                      isEven={index % 2 === 0}
                    />
                  ))
                )}
              </tbody>
            </table>
          </div>
          <ScrollBar orientation="horizontal" />
        </ScrollArea>
      </Card>
    </motion.div>
  );
}

/**
 * Column header with skill name and tooltip
 */
function SkillColumnHeader({ skill }: { skill: SkillMatrixSkill }) {
  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <div className="flex flex-col items-center gap-1 cursor-help">
            <span className="text-xs font-medium truncate max-w-[80px]">{skill.name}</span>
            {skill.isGlobal && (
              <Badge variant="outline" className="text-[10px] px-1 py-0">
                Global
              </Badge>
            )}
          </div>
        </TooltipTrigger>
        <TooltipContent>
          <div className="max-w-[200px]">
            <p className="font-medium">{skill.name}</p>
            {skill.description && (
              <p className="text-xs text-muted-foreground mt-1">{skill.description}</p>
            )}
            {skill.category && (
              <Badge variant="secondary" className="mt-1 text-xs">
                {skill.category}
              </Badge>
            )}
          </div>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}

/**
 * Single row in the matrix
 */
interface SkillMatrixRowComponentProps {
  row: SkillMatrixRow;
  skills: SkillMatrixSkill[];
  editable: boolean;
  onLevelChange?: (employeeId: string, skillId: string, newLevel: SkillLevelValue) => void;
  locale: string;
  isEven: boolean;
}

function SkillMatrixRowComponent({
  row,
  skills,
  editable,
  onLevelChange,
  locale,
  isEven,
}: SkillMatrixRowComponentProps) {
  const employee = row.employee;
  const fullName = `${employee.user.firstName} ${employee.user.lastName}`;

  return (
    <tr className={cn('border-b', isEven ? 'bg-background' : 'bg-muted/30')}>
      <td className="sticky left-0 z-10 p-3 bg-inherit">
        <div className="flex flex-col">
          <span className="font-medium text-sm">{fullName}</span>
          {employee.position && (
            <span className="text-xs text-muted-foreground">{employee.position}</span>
          )}
        </div>
      </td>
      {skills.map((skill) => {
        const entry = row.skills[skill.id] || { level: 0 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null };
        return (
          <td key={skill.id} className="p-0 text-center">
            <SkillCell
              entry={entry}
              employeeId={employee.id}
              skillId={skill.id}
              editable={editable}
              onLevelChange={onLevelChange}
              locale={locale}
            />
          </td>
        );
      })}
    </tr>
  );
}

/**
 * Loading skeleton for the matrix
 */
function SkillMatrixSkeleton() {
  return (
    <div className="space-y-4">
      <Card>
        <CardHeader className="pb-3">
          <Skeleton className="h-6 w-48" />
          <Skeleton className="h-4 w-32 mt-2" />
        </CardHeader>
        <CardContent>
          <div className="flex gap-3">
            {[0, 1, 2, 3, 4].map((i) => (
              <Skeleton key={i} className="h-6 w-20" />
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-4">
          <div className="space-y-3">
            {[0, 1, 2, 3, 4].map((row) => (
              <div key={row} className="flex items-center gap-4">
                <Skeleton className="h-10 w-40" />
                <div className="flex gap-2">
                  {[0, 1, 2, 3, 4, 5].map((cell) => (
                    <Skeleton key={cell} className="h-10 w-10 rounded-full" />
                  ))}
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
