'use client';

import { useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  ArrowLeft,
  Download,
  Upload,
  RefreshCw,
  Settings,
  BarChart3,
  Users,
  AlertTriangle,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { PageTransition } from '@/components/layout/page-transition';
import { useToast } from '@/hooks/use-toast';
import {
  SkillMatrixGrid,
  SkillGapChart,
  SkillGapSummary,
} from '@/components/lean/skill-matrix';
import {
  useSkillMatrix,
  useSkillGapAnalysis,
  useBulkUpsertSkillEntries,
  type SkillMatrix,
  type SkillGapAnalysis,
} from '@/hooks/lean/use-skill-matrix';
import type { SkillLevelValue } from '@/hooks/lean/use-skills';

interface DepartmentSkillMatrixContentProps {
  locale: string;
  departmentId: string;
}

// Mock data for development
// TODO: Remove when API is connected
const mockMatrix: SkillMatrix = {
  department: {
    id: '1',
    name: 'IT & Entwicklung',
    code: 'IT',
  },
  skills: [
    { id: 's1', name: 'TypeScript', description: 'TypeScript programming', category: 'Frontend', isGlobal: false },
    { id: 's2', name: 'React', description: 'React framework', category: 'Frontend', isGlobal: false },
    { id: 's3', name: 'Next.js', description: 'Next.js framework', category: 'Frontend', isGlobal: false },
    { id: 's4', name: 'Node.js', description: 'Node.js runtime', category: 'Backend', isGlobal: false },
    { id: 's5', name: 'PostgreSQL', description: 'PostgreSQL database', category: 'Backend', isGlobal: false },
    { id: 's6', name: 'Docker', description: 'Containerization', category: 'DevOps', isGlobal: true },
    { id: 's7', name: 'Git', description: 'Version control', category: 'Tools', isGlobal: true },
    { id: 's8', name: 'Scrum', description: 'Agile methodology', category: 'Process', isGlobal: true },
  ],
  matrix: [
    {
      employee: {
        id: 'e1',
        employeeNumber: 'EMP001',
        position: 'Senior Developer',
        user: { id: 'u1', firstName: 'Max', lastName: 'Mustermann', email: 'max@example.com' },
      },
      skills: {
        s1: { level: 4 as SkillLevelValue, assessedAt: '2024-01-15', assessedBy: { id: 'a1', firstName: 'Admin', lastName: 'User' }, notes: null },
        s2: { level: 4 as SkillLevelValue, assessedAt: '2024-01-15', assessedBy: { id: 'a1', firstName: 'Admin', lastName: 'User' }, notes: null },
        s3: { level: 3 as SkillLevelValue, assessedAt: '2024-01-15', assessedBy: { id: 'a1', firstName: 'Admin', lastName: 'User' }, notes: null },
        s4: { level: 3 as SkillLevelValue, assessedAt: '2024-01-15', assessedBy: null, notes: null },
        s5: { level: 2 as SkillLevelValue, assessedAt: '2024-01-10', assessedBy: null, notes: null },
        s6: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s7: { level: 4 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s8: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
      },
    },
    {
      employee: {
        id: 'e2',
        employeeNumber: 'EMP002',
        position: 'Junior Developer',
        user: { id: 'u2', firstName: 'Anna', lastName: 'Schmidt', email: 'anna@example.com' },
      },
      skills: {
        s1: { level: 2 as SkillLevelValue, assessedAt: '2024-01-20', assessedBy: null, notes: null },
        s2: { level: 2 as SkillLevelValue, assessedAt: '2024-01-20', assessedBy: null, notes: null },
        s3: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: 'In training' },
        s4: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s5: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s6: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s7: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s8: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
      },
    },
    {
      employee: {
        id: 'e3',
        employeeNumber: 'EMP003',
        position: 'Backend Developer',
        user: { id: 'u3', firstName: 'Peter', lastName: 'Mueller', email: 'peter@example.com' },
      },
      skills: {
        s1: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s2: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s3: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s4: { level: 4 as SkillLevelValue, assessedAt: '2024-01-05', assessedBy: null, notes: 'Expert' },
        s5: { level: 4 as SkillLevelValue, assessedAt: '2024-01-05', assessedBy: null, notes: null },
        s6: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s7: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s8: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
      },
    },
    {
      employee: {
        id: 'e4',
        employeeNumber: 'EMP004',
        position: 'DevOps Engineer',
        user: { id: 'u4', firstName: 'Lisa', lastName: 'Weber', email: 'lisa@example.com' },
      },
      skills: {
        s1: { level: 2 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s2: { level: 1 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s3: { level: 0 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s4: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s5: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s6: { level: 4 as SkillLevelValue, assessedAt: '2024-01-08', assessedBy: null, notes: 'Trainer' },
        s7: { level: 4 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
        s8: { level: 3 as SkillLevelValue, assessedAt: null, assessedBy: null, notes: null },
      },
    },
  ],
};

const mockGapAnalysis: SkillGapAnalysis[] = [
  { skillId: 's3', skillName: 'Next.js', category: 'Frontend', targetLevel: 2, averageLevel: 1.25, gap: 0.75, employeesBelow: 2, employeesAtOrAbove: 2, totalEmployees: 4 },
  { skillId: 's4', skillName: 'Node.js', category: 'Backend', targetLevel: 2, averageLevel: 2.75, gap: -0.75, employeesBelow: 1, employeesAtOrAbove: 3, totalEmployees: 4 },
  { skillId: 's1', skillName: 'TypeScript', category: 'Frontend', targetLevel: 2, averageLevel: 2.75, gap: -0.75, employeesBelow: 0, employeesAtOrAbove: 4, totalEmployees: 4 },
  { skillId: 's5', skillName: 'PostgreSQL', category: 'Backend', targetLevel: 2, averageLevel: 2.5, gap: -0.5, employeesBelow: 1, employeesAtOrAbove: 3, totalEmployees: 4 },
  { skillId: 's2', skillName: 'React', category: 'Frontend', targetLevel: 2, averageLevel: 2.25, gap: -0.25, employeesBelow: 1, employeesAtOrAbove: 3, totalEmployees: 4 },
  { skillId: 's8', skillName: 'Scrum', category: 'Process', targetLevel: 2, averageLevel: 2.25, gap: -0.25, employeesBelow: 0, employeesAtOrAbove: 4, totalEmployees: 4 },
  { skillId: 's6', skillName: 'Docker', category: 'DevOps', targetLevel: 2, averageLevel: 2.75, gap: -0.75, employeesBelow: 1, employeesAtOrAbove: 3, totalEmployees: 4 },
  { skillId: 's7', skillName: 'Git', category: 'Tools', targetLevel: 2, averageLevel: 3.25, gap: -1.25, employeesBelow: 0, employeesAtOrAbove: 4, totalEmployees: 4 },
];

/**
 * Department skill matrix content
 * Shows the matrix grid and gap analysis for a specific department
 */
export function DepartmentSkillMatrixContent({
  locale,
  departmentId,
}: DepartmentSkillMatrixContentProps) {
  const t = useTranslations('lean');
  const tCommon = useTranslations('common');
  const { toast } = useToast();

  const [targetLevel, setTargetLevel] = useState<number>(2);
  const [pendingChanges, setPendingChanges] = useState<
    Map<string, { employeeId: string; skillId: string; level: SkillLevelValue }>
  >(new Map());

  // API hooks - using mock data for now
  // const { data: matrix, isLoading: matrixLoading } = useSkillMatrix(departmentId);
  // const { data: gapAnalysis, isLoading: gapLoading } = useSkillGapAnalysis(departmentId, targetLevel);
  const bulkUpsert = useBulkUpsertSkillEntries();

  // Use mock data for development
  const matrix = mockMatrix;
  const matrixLoading = false;
  const gapAnalysis = mockGapAnalysis;
  const gapLoading = false;

  // Handle level change with optimistic update
  const handleLevelChange = useCallback(
    (employeeId: string, skillId: string, newLevel: SkillLevelValue) => {
      const key = `${employeeId}-${skillId}`;
      setPendingChanges((prev) => {
        const next = new Map(prev);
        next.set(key, { employeeId, skillId, level: newLevel });
        return next;
      });

      // TODO: Debounce and batch API calls
      toast({
        title: t('skillMatrix.levelUpdated'),
        description: t('skillMatrix.levelUpdatedDescription'),
      });
    },
    [t, toast]
  );

  // Save all pending changes
  const handleSaveChanges = useCallback(async () => {
    if (pendingChanges.size === 0) return;

    const entries = Array.from(pendingChanges.values());

    try {
      await bulkUpsert.mutateAsync({ entries });
      setPendingChanges(new Map());
      toast({
        title: tCommon('success'),
        description: t('skillMatrix.changesSaved'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('skillMatrix.saveError'),
        variant: 'destructive',
      });
    }
  }, [pendingChanges, bulkUpsert, t, tCommon, toast]);

  if (matrixLoading) {
    return <LoadingSkeleton />;
  }

  if (!matrix) {
    return (
      <PageTransition>
        <div className="flex flex-col items-center justify-center py-12">
          <AlertTriangle className="h-12 w-12 text-muted-foreground/50" />
          <p className="mt-4 text-muted-foreground">{t('skillMatrix.notFound')}</p>
          <Link href={`/${locale}/lean/skill-matrix`}>
            <Button variant="outline" className="mt-4 gap-2">
              <ArrowLeft className="h-4 w-4" />
              {tCommon('back')}
            </Button>
          </Link>
        </div>
      </PageTransition>
    );
  }

  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 className="flex items-center gap-4">
            <Link href={`/${locale}/lean/skill-matrix`}>
              <Button variant="ghost" size="icon">
                <ArrowLeft className="h-4 w-4" />
              </Button>
            </Link>
            <div>
              <h1 className="text-3xl font-bold tracking-tight">{matrix.department.name}</h1>
              <p className="text-muted-foreground">
                {t('skillMatrix.subtitle', {
                  employees: matrix.matrix.length,
                  skills: matrix.skills.length,
                })}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {pendingChanges.size > 0 && (
              <Badge variant="secondary">
                {pendingChanges.size} {t('skillMatrix.unsavedChanges')}
              </Badge>
            )}
            <Button
              variant="outline"
              size="sm"
              className="gap-2"
              onClick={handleSaveChanges}
              disabled={pendingChanges.size === 0 || bulkUpsert.isPending}
            >
              {bulkUpsert.isPending ? (
                <RefreshCw className="h-4 w-4 animate-spin" />
              ) : (
                <Download className="h-4 w-4" />
              )}
              {tCommon('save')}
            </Button>
            <Button variant="outline" size="sm" className="gap-2">
              <Upload className="h-4 w-4" />
              {tCommon('export')}
            </Button>
            <Button variant="outline" size="icon" className="h-9 w-9">
              <Settings className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Tabs for Matrix and Analysis */}
        <Tabs defaultValue="matrix" className="space-y-4">
          <TabsList>
            <TabsTrigger value="matrix" className="gap-2">
              <Users className="h-4 w-4" />
              {t('skillMatrix.matrixView')}
            </TabsTrigger>
            <TabsTrigger value="analysis" className="gap-2">
              <BarChart3 className="h-4 w-4" />
              {t('skillMatrix.gapAnalysis')}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="matrix" className="space-y-4">
            <SkillMatrixGrid
              matrix={matrix}
              isLoading={matrixLoading}
              editable={true}
              onLevelChange={handleLevelChange}
              locale={locale}
            />
          </TabsContent>

          <TabsContent value="analysis" className="space-y-4">
            {/* Target Level Selector */}
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base">{t('skillMatrix.gapAnalysisSettings')}</CardTitle>
                    <CardDescription>{t('skillMatrix.gapAnalysisSettingsDescription')}</CardDescription>
                  </div>
                  <Select
                    value={String(targetLevel)}
                    onValueChange={(v) => setTargetLevel(Number(v))}
                  >
                    <SelectTrigger className="w-[140px]">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">{t('skillMatrix.levels.1')}</SelectItem>
                      <SelectItem value="2">{t('skillMatrix.levels.2')}</SelectItem>
                      <SelectItem value="3">{t('skillMatrix.levels.3')}</SelectItem>
                      <SelectItem value="4">{t('skillMatrix.levels.4')}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardHeader>
            </Card>

            {/* Gap Summary */}
            <SkillGapSummary data={gapAnalysis || []} />

            {/* Gap Chart */}
            <SkillGapChart
              data={gapAnalysis || []}
              targetLevel={targetLevel}
              isLoading={gapLoading}
            />
          </TabsContent>
        </Tabs>
      </div>
    </PageTransition>
  );
}

/**
 * Loading skeleton
 */
function LoadingSkeleton() {
  return (
    <PageTransition>
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-10 w-10 rounded-full" />
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-4 w-32 mt-2" />
          </div>
        </div>

        <Skeleton className="h-10 w-64" />

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