'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  Users,
  Building2,
  ChevronRight,
  Search,
  TrendingUp,
  TrendingDown,
  Minus,
  Plus,
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { PageTransition } from '@/components/layout/page-transition';
import { SkillLevelLegend } from '@/components/lean/skill-matrix';

interface SkillMatrixOverviewContentProps {
  locale: string;
}

// Mock departments with skill matrix stats
// TODO: Replace with API call
const mockDepartments = [
  {
    id: '1',
    name: 'IT & Entwicklung',
    code: 'IT',
    employeeCount: 24,
    skillCount: 18,
    averageLevel: 2.8,
    coverage: 92,
    trend: 'up' as const,
  },
  {
    id: '2',
    name: 'Personal',
    code: 'HR',
    employeeCount: 8,
    skillCount: 12,
    averageLevel: 2.5,
    coverage: 88,
    trend: 'stable' as const,
  },
  {
    id: '3',
    name: 'Vertrieb',
    code: 'SALES',
    employeeCount: 32,
    skillCount: 15,
    averageLevel: 2.2,
    coverage: 75,
    trend: 'down' as const,
  },
  {
    id: '4',
    name: 'Lager & Logistik',
    code: 'LOG',
    employeeCount: 45,
    skillCount: 20,
    averageLevel: 2.4,
    coverage: 80,
    trend: 'up' as const,
  },
  {
    id: '5',
    name: 'Finanzen',
    code: 'FIN',
    employeeCount: 6,
    skillCount: 10,
    averageLevel: 3.1,
    coverage: 95,
    trend: 'stable' as const,
  },
];

/**
 * Skill Matrix overview page content
 * Shows list of departments with skill matrix summary
 */
export function SkillMatrixOverviewContent({ locale }: SkillMatrixOverviewContentProps) {
  const t = useTranslations('lean');
  const tCommon = useTranslations('common');
  const [searchQuery, setSearchQuery] = useState('');
  const [isLoading] = useState(false);

  // Filter departments by search
  const filteredDepartments = mockDepartments.filter((dept) => {
    if (!searchQuery.trim()) return true;
    const query = searchQuery.toLowerCase();
    return (
      dept.name.toLowerCase().includes(query) || dept.code.toLowerCase().includes(query)
    );
  });

  // Calculate overall stats
  const totalEmployees = mockDepartments.reduce((sum, d) => sum + d.employeeCount, 0);
  const avgCoverage = Math.round(
    mockDepartments.reduce((sum, d) => sum + d.coverage, 0) / mockDepartments.length
  );
  const avgLevel = (
    mockDepartments.reduce((sum, d) => sum + d.averageLevel, 0) / mockDepartments.length
  ).toFixed(1);

  return (
    <PageTransition>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{t('skillMatrix.title')}</h1>
            <p className="text-muted-foreground">{t('skillMatrix.description')}</p>
          </div>
          <Button className="gap-2">
            <Plus className="h-4 w-4" />
            {t('skillMatrix.addSkill')}
          </Button>
        </div>

        {/* Overall Stats */}
        <div className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t('skillMatrix.totalEmployees')}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{totalEmployees}</div>
              <p className="text-xs text-muted-foreground">
                {t('skillMatrix.inDepartments', { count: mockDepartments.length })}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t('skillMatrix.avgCoverage')}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{avgCoverage}%</div>
              <div className="flex items-center text-xs text-green-600">
                <TrendingUp className="h-3 w-3 mr-1" />
                +3% {t('skillMatrix.vsLastMonth')}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t('skillMatrix.avgLevel')}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{avgLevel}</div>
              <p className="text-xs text-muted-foreground">{t('skillMatrix.targetLevel')}: 2.5</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t('skillMatrix.trainers')}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">12</div>
              <p className="text-xs text-muted-foreground">Level 4 ({t('skillMatrix.levels.4')})</p>
            </CardContent>
          </Card>
        </div>

        {/* Search and Legend */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex flex-col sm:flex-row sm:items-center gap-4">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder={`${t('skillMatrix.searchDepartment')}...`}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>
          </CardHeader>
          <CardContent className="pb-3">
            <SkillLevelLegend />
          </CardContent>
        </Card>

        {/* Department Cards */}
        {isLoading ? (
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {[1, 2, 3, 4, 5, 6].map((i) => (
              <Card key={i}>
                <CardHeader>
                  <Skeleton className="h-6 w-32" />
                  <Skeleton className="h-4 w-48 mt-2" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-20 w-full" />
                </CardContent>
              </Card>
            ))}
          </div>
        ) : filteredDepartments.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12">
              <Building2 className="h-12 w-12 text-muted-foreground/50" />
              <p className="mt-4 text-muted-foreground">{t('skillMatrix.noDepartmentsFound')}</p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {filteredDepartments.map((dept) => (
              <DepartmentCard key={dept.id} department={dept} locale={locale} t={t} />
            ))}
          </div>
        )}
      </div>
    </PageTransition>
  );
}

/**
 * Department card with skill matrix summary
 */
interface DepartmentCardProps {
  department: (typeof mockDepartments)[0];
  locale: string;
  t: ReturnType<typeof import('next-intl').useTranslations>;
}

function DepartmentCard({ department, locale, t }: DepartmentCardProps) {
  const TrendIcon =
    department.trend === 'up' ? TrendingUp : department.trend === 'down' ? TrendingDown : Minus;
  const trendColor =
    department.trend === 'up'
      ? 'text-green-600'
      : department.trend === 'down'
      ? 'text-red-600'
      : 'text-muted-foreground';

  const coverageColor =
    department.coverage >= 90
      ? 'text-green-600 bg-green-100 dark:bg-green-900/30'
      : department.coverage >= 75
      ? 'text-yellow-600 bg-yellow-100 dark:bg-yellow-900/30'
      : 'text-red-600 bg-red-100 dark:bg-red-900/30';

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <Link href={`/${locale}/lean/skill-matrix/${department.id}`}>
        <Card className="hover:shadow-md transition-shadow cursor-pointer h-full">
          <CardHeader className="pb-3">
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <Building2 className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <CardTitle className="text-base">{department.name}</CardTitle>
                  <CardDescription>{department.code}</CardDescription>
                </div>
              </div>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
                  <Users className="h-4 w-4" />
                  <span>{department.employeeCount}</span>
                </div>
                <p className="text-xs text-muted-foreground">{t('skillMatrix.employees')}</p>
              </div>
              <div>
                <Badge variant="secondary" className={coverageColor}>
                  {department.coverage}%
                </Badge>
                <p className="text-xs text-muted-foreground mt-1">{t('skillMatrix.coverage')}</p>
              </div>
              <div>
                <div className="text-sm font-medium">{department.averageLevel.toFixed(1)}</div>
                <p className="text-xs text-muted-foreground">{t('skillMatrix.avgLevel')}</p>
              </div>
              <div>
                <div className={`flex items-center gap-1 text-sm ${trendColor}`}>
                  <TrendIcon className="h-4 w-4" />
                  <span>{t(`skillMatrix.trend.${department.trend}`)}</span>
                </div>
                <p className="text-xs text-muted-foreground">{t('skillMatrix.trend.label')}</p>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t">
              <p className="text-xs text-muted-foreground">
                {department.skillCount} {t('skills')}
              </p>
            </div>
          </CardContent>
        </Card>
      </Link>
    </motion.div>
  );
}
