'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { format } from 'date-fns';
import { de } from 'date-fns/locale';
import {
  ArrowLeft,
  Edit,
  Mail,
  Phone,
  Building2,
  Calendar,
  Clock,
  Briefcase,
  MapPin,
  AlertCircle,
  User,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { PageTransition } from '@/components/layout/page-transition';
import { cn } from '@/lib/utils';
import {
  useEmployee,
  EMPLOYMENT_STATUS_COLORS,
} from '@/hooks/hr/use-employees';

interface EmployeeDetailContentProps {
  locale: string;
  employeeId: string;
}

/**
 * Employee detail page content
 * Shows employee information in tabs: Overview, Time Account, Absences
 */
export function EmployeeDetailContent({
  locale,
  employeeId,
}: EmployeeDetailContentProps) {
  const t = useTranslations('hr');
  const tContract = useTranslations('hr.contractType');
  const tStatus = useTranslations('hr.employeeStatus');
  const tCommon = useTranslations('common');

  const [activeTab, setActiveTab] = useState('overview');

  const { data: employee, isLoading, error } = useEmployee(employeeId);

  // Loading state
  if (isLoading) {
    return (
      <PageTransition>
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <Skeleton className="h-10 w-10" />
            <Skeleton className="h-8 w-48" />
          </div>
          <div className="grid gap-6 md:grid-cols-3">
            <Skeleton className="h-[300px]" />
            <Skeleton className="h-[300px] md:col-span-2" />
          </div>
        </div>
      </PageTransition>
    );
  }

  // Error state
  if (error || !employee) {
    return (
      <PageTransition>
        <div className="flex flex-col items-center justify-center py-12">
          <AlertCircle className="h-12 w-12 text-destructive mb-4" />
          <h2 className="text-xl font-semibold mb-2">{t('employeeNotFound')}</h2>
          <p className="text-muted-foreground mb-4">
            {t('employeeNotFoundDesc')}
          </p>
          <Link href={`/${locale}/hr/employees`}>
            <Button>
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t('backToList')}
            </Button>
          </Link>
        </div>
      </PageTransition>
    );
  }

  const initials = `${employee.firstName.charAt(0)}${employee.lastName.charAt(0)}`;
  const statusColors = EMPLOYMENT_STATUS_COLORS[employee.status];

  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}/hr/employees`}>
              <Button variant="ghost" size="icon">
                <ArrowLeft className="h-4 w-4" />
              </Button>
            </Link>
            <div>
              <h1 className="text-3xl font-bold tracking-tight">
                {employee.firstName} {employee.lastName}
              </h1>
              <p className="text-muted-foreground">{employee.employeeNumber}</p>
            </div>
          </div>
          <Link href={`/${locale}/hr/employees/${employee.id}?edit=true`}>
            <Button className="gap-2">
              <Edit className="h-4 w-4" />
              {tCommon('edit')}
            </Button>
          </Link>
        </div>

        {/* Content */}
        <div className="grid gap-6 md:grid-cols-3">
          {/* Sidebar - Employee Card */}
          <Card>
            <CardContent className="pt-6">
              <div className="flex flex-col items-center text-center">
                <Avatar className="h-24 w-24 mb-4">
                  <AvatarImage
                    src={employee.avatarUrl}
                    alt={`${employee.firstName} ${employee.lastName}`}
                  />
                  <AvatarFallback className="bg-primary/10 text-primary text-2xl font-bold">
                    {initials}
                  </AvatarFallback>
                </Avatar>
                <h2 className="text-xl font-semibold">
                  {employee.firstName} {employee.lastName}
                </h2>
                <p className="text-muted-foreground">{employee.position}</p>
                <Badge
                  variant="outline"
                  className={cn(
                    'mt-2 font-medium border',
                    statusColors.bg,
                    statusColors.text,
                    statusColors.border
                  )}
                >
                  {tStatus(employee.status)}
                </Badge>
              </div>

              <Separator className="my-6" />

              <div className="space-y-4">
                <div className="flex items-center gap-3">
                  <Mail className="h-4 w-4 text-muted-foreground" />
                  <a
                    href={`mailto:${employee.email}`}
                    className="text-sm hover:underline"
                  >
                    {employee.email}
                  </a>
                </div>
                {employee.phone && (
                  <div className="flex items-center gap-3">
                    <Phone className="h-4 w-4 text-muted-foreground" />
                    <a
                      href={`tel:${employee.phone}`}
                      className="text-sm hover:underline"
                    >
                      {employee.phone}
                    </a>
                  </div>
                )}
                <div className="flex items-center gap-3">
                  <Building2 className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">{employee.department?.name}</span>
                </div>
                {employee.manager && (
                  <div className="flex items-center gap-3">
                    <User className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm">
                      {t('manager')}: {employee.manager.firstName}{' '}
                      {employee.manager.lastName}
                    </span>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Main Content - Tabs */}
          <div className="md:col-span-2">
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="w-full justify-start">
                <TabsTrigger value="overview">{t('tabs.overview')}</TabsTrigger>
                <TabsTrigger value="timeAccount">
                  {t('tabs.timeAccount')}
                </TabsTrigger>
                <TabsTrigger value="absences">{t('tabs.absences')}</TabsTrigger>
              </TabsList>

              {/* Overview Tab */}
              <TabsContent value="overview" className="space-y-6 mt-6">
                {/* Employment Details */}
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">
                      {t('employmentDetails')}
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="grid gap-4 sm:grid-cols-2">
                    <div>
                      <p className="text-sm text-muted-foreground">
                        {t('contractType.label')}
                      </p>
                      <p className="font-medium">
                        {tContract(employee.contractType)}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">
                        {t('weeklyHours')}
                      </p>
                      <p className="font-medium">{employee.weeklyHours} h</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">
                        {t('hireDate')}
                      </p>
                      <p className="font-medium">
                        {format(new Date(employee.hireDate), 'PPP', {
                          locale: locale === 'de' ? de : undefined,
                        })}
                      </p>
                    </div>
                    {employee.terminationDate && (
                      <div>
                        <p className="text-sm text-muted-foreground">
                          {t('terminationDate')}
                        </p>
                        <p className="font-medium text-destructive">
                          {format(new Date(employee.terminationDate), 'PPP', {
                            locale: locale === 'de' ? de : undefined,
                          })}
                        </p>
                      </div>
                    )}
                    <div>
                      <p className="text-sm text-muted-foreground">
                        {t('roles')}
                      </p>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {employee.roles.map((role) => (
                          <Badge key={role} variant="secondary">
                            {role}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Address */}
                {employee.address && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg">{t('address')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-start gap-3">
                        <MapPin className="h-4 w-4 text-muted-foreground mt-1" />
                        <div>
                          <p>{employee.address.street}</p>
                          <p>
                            {employee.address.zipCode} {employee.address.city}
                          </p>
                          <p>{employee.address.country}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {/* Emergency Contact */}
                {employee.emergencyContact && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg">
                        {t('emergencyContact')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="grid gap-4 sm:grid-cols-2">
                      <div>
                        <p className="text-sm text-muted-foreground">
                          {t('emergencyName')}
                        </p>
                        <p className="font-medium">
                          {employee.emergencyContact.name}
                        </p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">
                          {t('emergencyPhone')}
                        </p>
                        <p className="font-medium">
                          {employee.emergencyContact.phone}
                        </p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">
                          {t('emergencyRelationship')}
                        </p>
                        <p className="font-medium">
                          {employee.emergencyContact.relationship}
                        </p>
                      </div>
                    </CardContent>
                  </Card>
                )}
              </TabsContent>

              {/* Time Account Tab */}
              <TabsContent value="timeAccount" className="space-y-6 mt-6">
                <div className="grid gap-4 sm:grid-cols-2">
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        {t('overtimeBalance')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div
                        className={cn(
                          'text-2xl font-bold',
                          employee.overtimeBalance > 0
                            ? 'text-green-600'
                            : employee.overtimeBalance < 0
                            ? 'text-red-600'
                            : ''
                        )}
                      >
                        {employee.overtimeBalance > 0 ? '+' : ''}
                        {employee.overtimeBalance.toFixed(1)} h
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        {t('weeklyTarget')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {employee.weeklyHours} h
                      </div>
                    </CardContent>
                  </Card>
                </div>

                <Card>
                  <CardContent className="pt-6">
                    <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                      <Clock className="h-12 w-12 mb-4 opacity-50" />
                      <p>{t('timeTracking.noData')}</p>
                      <p className="text-sm">{t('timeTracking.noDataDesc')}</p>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* Absences Tab */}
              <TabsContent value="absences" className="space-y-6 mt-6">
                <div className="grid gap-4 sm:grid-cols-3">
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        {t('vacationDaysTotal')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {employee.vacationDaysTotal}
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        {t('vacationDaysUsed')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {employee.vacationDaysUsed}
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        {t('vacationDaysRemaining')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold text-green-600">
                        {employee.vacationDaysTotal -
                          employee.vacationDaysUsed -
                          employee.vacationDaysPending}
                      </div>
                      {employee.vacationDaysPending > 0 && (
                        <p className="text-xs text-yellow-600">
                          +{employee.vacationDaysPending} {t('pending')}
                        </p>
                      )}
                    </CardContent>
                  </Card>
                </div>

                {/* Vacation Progress Bar */}
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">
                      {t('vacationOverview')}
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span>
                          {employee.vacationDaysUsed +
                            employee.vacationDaysPending}{' '}
                          / {employee.vacationDaysTotal} {t('daysUsed')}
                        </span>
                        <span>
                          {Math.round(
                            ((employee.vacationDaysUsed +
                              employee.vacationDaysPending) /
                              employee.vacationDaysTotal) *
                              100
                          )}
                          %
                        </span>
                      </div>
                      <div className="h-3 bg-muted rounded-full overflow-hidden">
                        <div
                          className="h-full bg-primary transition-all"
                          style={{
                            width: `${Math.min(
                              100,
                              ((employee.vacationDaysUsed +
                                employee.vacationDaysPending) /
                                employee.vacationDaysTotal) *
                                100
                            )}%`,
                          }}
                        />
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Absence List Placeholder */}
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                      <Calendar className="h-12 w-12 mb-4 opacity-50" />
                      <p>{t('absences.noData')}</p>
                      <p className="text-sm">{t('absences.noDataDesc')}</p>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </div>
    </PageTransition>
  );
}
