'use client';

import { useState, useCallback, useEffect, type ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { motion } from 'motion/react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { DatePicker } from '@/components/ui/date-picker';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import { EvaluationLoadingScreen } from '@/components/users/evaluation-loading-screen';
import { easeOutExpo, staggerContainer, staggerItem } from '@/lib/motion';
import { UserPerformance } from '@/components/forms/user-performance';
import { UserLoggedHoursViz } from '@/components/users/user-logged-hours-viz';
import { LoggedHoursImport } from '@/components/users/logged-hours-import';
import { UserAttendance } from '@/components/users/user-attendance';
import { UserReportCardWrapper } from '@/components/users/user-report-card-wrapper';
import { UserDetailExportMenu } from '@/components/users/user-detail-export-menu';
import { api } from '@/lib/store/api';
import { apiCall, apiErrorMessage } from '@/lib/store/api-call';
import { ItWorkHistory } from '@/components/users/it-work-history';
import { USER_ROLES, isDesignHead } from '@/lib/constants';
import { type User, type UserRole } from '@/lib/types';
import { formatDate as formatDateUtil, calculateEmploymentStatus, getEmploymentStatusBadgeColor } from '@/lib/date-utils';
import {
  ArrowLeft,
  User as UserIcon,
  Mail,
  Building,
  Calendar,
  Edit,
  TrendingUp,
  Clock,
  Phone,
  CalendarCheck,
  ClipboardList,
  Laptop,
  Palette,
} from 'lucide-react';

interface UserDetailClientProps {
  user: User | null;
}

const getRoleBadgeColor = (role: UserRole) => {
  const colors: Record<UserRole, string> = {
    SUPER_ADMIN: 'bg-red-500/10 text-red-700 border-red-500/20 dark:text-red-300',
    UPPER_MANAGEMENT: 'bg-primary/10 text-primary border-primary/20',
    MANAGER: 'bg-emerald-500/10 text-emerald-700 border-emerald-500/20 dark:text-emerald-300',
    UNIT_LEAD: 'bg-orange-500/10 text-orange-700 border-orange-500/20 dark:text-orange-300',
    MEMBER: 'bg-muted text-foreground border-border',
  };
  return colors[role];
};

// Hide TabsTrigger's default bg-card overlay so primary fill + contrast text stay visible
const TAB_TRIGGER_CLASS =
  'rounded-lg px-3 py-2.5 text-sm font-medium text-muted-foreground transition-colors ' +
  'hover:bg-background/80 hover:text-foreground ' +
  'data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm ' +
  'data-[state=active]:hover:bg-primary data-[state=active]:hover:text-primary-foreground ' +
  '[&>span[aria-hidden]]:hidden ' +
  '[&>span.relative]:inline-flex [&>span.relative]:min-w-0 [&>span.relative]:items-center [&>span.relative]:justify-center [&>span.relative]:gap-2';

const DETAIL_TABS = ['report-card', 'performance', 'logged-hours', 'work-history', 'attendance'] as const;

/** 1st of the month 11 months back, so the range covers the last 12 months (e.g. 15 Oct 2026 → 2025-11-01). */
const defaultDateFrom = () => {
  const now = new Date();
  const from = new Date(now.getFullYear(), now.getMonth() - 11, 1);
  return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-01`;
};

function AnimatedTabsContent({
  value,
  children,
  className = '',
  activeTab,
  previousTab,
  isAnimating,
  animationDirection,
}: {
  value: string;
  children: ReactNode;
  className?: string;
  activeTab: string;
  previousTab: string;
  isAnimating: boolean;
  animationDirection: 'left' | 'right';
}) {
  const isActive = activeTab === value;
  const wasActive = previousTab === value;

  if (!isActive && !wasActive) {
    return null;
  }

  const getAnimationClass = () => {
    if (isAnimating) {
      if (wasActive) {
        return animationDirection === 'right'
          ? 'animate-slide-out-left'
          : 'animate-slide-out-right';
      }
      if (isActive) {
        return animationDirection === 'right'
          ? 'animate-slide-in-right'
          : 'animate-slide-in-left';
      }
    }
    return '';
  };

  return (
    <div
      className={`transition-all duration-300 ${getAnimationClass()} ${isActive ? 'relative' : 'absolute inset-0'}`}
      style={{
        display: isActive || (isAnimating && wasActive) ? 'block' : 'none',
      }}
    >
      <TabsContent value={value} className={className}>
        {children}
      </TabsContent>
    </div>
  );
}

export function UserDetailClient({ user: initialUser }: UserDetailClientProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState('report-card');
  const [evaluationReady, setEvaluationReady] = useState(false);
  const [reportBoot, setReportBoot] = useState<{
    data: any | null;
    error: string | null;
    dateFrom: string;
    dateTo: string;
  } | null>(null);

  // Global date range filter — default last 12 months (1st of the month 11 months back) → today.
  const [dateFrom, setDateFrom] = useState(defaultDateFrom);
  const [dateTo, setDateTo] = useState(new Date().toISOString().split('T')[0]);

  // Bumped each time the Report Card tab is opened so it remounts and refetches
  // (the previous tab stays mounted for the slide animation, so it would otherwise keep stale scores).
  const [reportCardVisit, setReportCardVisit] = useState(0);

  // Splash-prefetched report card is only reusable for the range it was fetched with.
  const bootMatchesRange =
    reportBoot?.dateFrom === dateFrom && reportBoot?.dateTo === dateTo;

  // Reset evaluating sequence when navigating between employees
  useEffect(() => {
    setUser(initialUser);
    setEvaluationReady(false);
    setReportBoot(null);
    setDateFrom(defaultDateFrom());
    setDateTo(new Date().toISOString().split("T")[0]);
  }, [initialUser?.id]);

  // Prefetch report card during splash (parallel). Always keep the loader
  // visible for a fixed 3s so the transition feels consistent — no extra APIs.
  useEffect(() => {
    if (!initialUser?.id || evaluationReady) return;

    let cancelled = false;
    const splashMs = 3000;

    const splashTimer = window.setTimeout(() => {
      if (!cancelled) setEvaluationReady(true);
    }, splashMs);

    const savedTab =
      typeof window !== 'undefined'
        ? sessionStorage.getItem(`userDetailTab_${initialUser.id}`)
        : null;
    const landingTab =
      savedTab && DETAIL_TABS.includes(savedTab as (typeof DETAIL_TABS)[number])
        ? savedTab
        : 'report-card';

    if (landingTab === 'report-card') {
      (async () => {
        let data: any | null = null;
        let error: string | null = null;
        try {
          data = await apiCall(
            api.endpoints.getReportCard.initiate({
              userId: initialUser.id,
              startDate: dateFrom,
              endDate: dateTo,
            }),
          );
        } catch (err) {
          error = apiErrorMessage(err, 'An error occurred');
        }

        if (cancelled) return;
        setReportBoot({ data, error, dateFrom, dateTo });
      })();
    }

    return () => {
      cancelled = true;
      window.clearTimeout(splashTimer);
    };
    // Bootstrap once per employee with initial date range
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialUser?.id]);
  const [previousTab, setPreviousTab] = useState('report-card');
  const [animationDirection, setAnimationDirection] = useState<'left' | 'right'>('right');
  const [isAnimating, setIsAnimating] = useState(false);
  const [isEditingProfile, setIsEditingProfile] = useState(false);
  const [editingSection, setEditingSection] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [user, setUser] = useState(initialUser);
  const [loadedSections, setLoadedSections] = useState<Set<string>>(new Set(['basic']));
  const [sectionData, setSectionData] = useState<Record<string, any>>({});
  const { data: session } = useSession();

  // Load section data on-demand
  const loadSectionData = useCallback(async (section: string) => {
    setLoadedSections(current => {
      if (current.has(section) || !user?.id) return current;
      
      // Start loading in the background
      apiCall(api.endpoints.getUserProfile.initiate({ id: user.id, section }))
        .then((data) => {
          if (data) {
            setSectionData((prev) => ({ ...prev, [section]: data }));
          }
        })
        .catch(() => {
          // Silently fail for better UX
        });
      
      // Immediately mark as loading to prevent duplicate requests
      return new Set([...Array.from(current), section]);
    });
  }, [user?.id]);

  // Load data when tab changes
  useEffect(() => {
    if (activeTab === 'profile') {
      loadSectionData('profile');
    }
  }, [activeTab, loadSectionData]);

  // Persist active tab in sessionStorage to prevent tab jumping
  useEffect(() => {
    const savedTab = sessionStorage.getItem(`userDetailTab_${user?.id}`);
    if (savedTab && DETAIL_TABS.includes(savedTab as (typeof DETAIL_TABS)[number])) {
      setActiveTab(savedTab);
      setPreviousTab(savedTab);
    }
  }, [user?.id]);

  const handleTabChange = useCallback((value: string) => {
    // Define tab order for animation direction (IT uses work-history instead of logged-hours)
    const tabOrder = ['report-card', 'performance', 'logged-hours', 'work-history', 'attendance'];
    const currentIndex = tabOrder.indexOf(activeTab);
    const newIndex = tabOrder.indexOf(value);
    
    // Determine animation direction
    const direction = newIndex > currentIndex ? 'right' : 'left';
    
    // Set animation state
    setIsAnimating(true);
    setAnimationDirection(direction);
    setPreviousTab(activeTab);

    // The splash-prefetched report card is only for the first view; once the user
    // leaves the tab (and may edit KPIs elsewhere), coming back fetches fresh data.
    if (activeTab === 'report-card' && value !== 'report-card') {
      setReportBoot(null);
    }
    if (value === 'report-card' && activeTab !== 'report-card') {
      setReportCardVisit((visit) => visit + 1);
    }

    // Change tab with slight delay for smooth transition
    setTimeout(() => {
      setActiveTab(value);
      if (user?.id) {
        sessionStorage.setItem(`userDetailTab_${user.id}`, value);
      }
    }, 50);
    
    // Reset animation state
    setTimeout(() => {
      setIsAnimating(false);
    }, 400);
  }, [activeTab, user?.id]);

  const handleSectionEdit = useCallback(async (section: string, data: any) => {
    if (!user?.id) return;
    setIsLoading(true);
    try {
      const updatedData = await apiCall(
        api.endpoints.updateUserProfile.initiate({
          id: user.id,
          body: { section, data },
        }),
      );

      // Update local state with the new data
      setUser(prevUser => {
        if (!prevUser) return prevUser;

        // Create a new user object with updated data
        const updatedUser = { ...prevUser };

        // Apply the section-specific updates
        switch (section) {
          case 'personalInfo':
            Object.assign(updatedUser, {
              dateOfBirth: data.dateOfBirth !== undefined ? data.dateOfBirth : prevUser.dateOfBirth,
              gender: data.gender !== undefined ? data.gender : prevUser.gender,
              maritalStatus: data.maritalStatus !== undefined ? data.maritalStatus : prevUser.maritalStatus,
              bloodGroup: data.bloodGroup !== undefined ? data.bloodGroup : prevUser.bloodGroup,
              nationality: data.nationality !== undefined ? data.nationality : prevUser.nationality,
              personalEmail: data.personalEmail !== undefined ? data.personalEmail : prevUser.personalEmail,
              emergencyContactName: data.emergencyContactName !== undefined ? data.emergencyContactName : prevUser.emergencyContactName,
              emergencyContactPhone: data.emergencyContactPhone !== undefined ? data.emergencyContactPhone : prevUser.emergencyContactPhone,
              emergencyContactRelation: data.emergencyContactRelation !== undefined ? data.emergencyContactRelation : prevUser.emergencyContactRelation,
            });
            break;
          case 'addressInfo':
            Object.assign(updatedUser, {
              currentAddressStreet: data.currentAddressStreet !== undefined ? data.currentAddressStreet : prevUser.currentAddressStreet,
              currentAddressCity: data.currentAddressCity !== undefined ? data.currentAddressCity : prevUser.currentAddressCity,
              currentAddressState: data.currentAddressState !== undefined ? data.currentAddressState : prevUser.currentAddressState,
              currentAddressZipCode: data.currentAddressZipCode !== undefined ? data.currentAddressZipCode : prevUser.currentAddressZipCode,
              currentAddressCountry: data.currentAddressCountry !== undefined ? data.currentAddressCountry : prevUser.currentAddressCountry,
            });
            break;
          case 'familyInfo':
            Object.assign(updatedUser, {
              spouseName: data.spouseName !== undefined ? data.spouseName : prevUser.spouseName,
              spouseOccupation: data.spouseOccupation !== undefined ? data.spouseOccupation : prevUser.spouseOccupation,
              fatherName: data.fatherName !== undefined ? data.fatherName : prevUser.fatherName,
              motherName: data.motherName !== undefined ? data.motherName : prevUser.motherName,
              children: data.children !== undefined ? data.children : prevUser.children,
            });
            break;
          case 'professionalLinks':
            Object.assign(updatedUser, {
              linkedinUrl: data.linkedinUrl !== undefined ? data.linkedinUrl : prevUser.linkedinUrl,
              githubUrl: data.githubUrl !== undefined ? data.githubUrl : prevUser.githubUrl,
              portfolioUrl: data.portfolioUrl !== undefined ? data.portfolioUrl : prevUser.portfolioUrl,
            });
            break;
          case 'education':
            updatedUser.education = data.education !== undefined ? data.education : prevUser.education;
            break;
          case 'workExperience':
            updatedUser.workExperience = data.workExperience !== undefined ? data.workExperience : prevUser.workExperience;
            break;
          case 'certifications':
            updatedUser.certifications = data.certifications !== undefined ? data.certifications : prevUser.certifications;
            break;
          case 'skills':
            updatedUser.skills = data.skills !== undefined ? data.skills : prevUser.skills;
            break;
          case 'techStack':
            updatedUser.techStack = data.techStack !== undefined ? data.techStack : prevUser.techStack;
            break;
          case 'designSubTeam':
            updatedUser.designSubTeam = data.designSubTeam !== undefined ? data.designSubTeam : prevUser.designSubTeam;
            break;
        }

        return updatedUser;
      });

      // Show professional success toast
      toast({
        title: "✅ Profile Updated Successfully",
        description: `Your ${getSectionDisplayName(section)} has been updated and saved.`,
        duration: 4000,
        className: "border-green-200 bg-green-50",
      });

      // Close the edit mode
      setEditingSection(null);
      setIsEditingProfile(false);
    } catch (error) {
      console.error('Error updating profile:', error);

      // Show professional error toast
      toast({
        title: "❌ Update Failed",
        description: (error as Error).message || 'An unexpected error occurred while updating your profile. Please try again.',
        variant: "destructive",
        duration: 6000,
      });
    } finally {
      setIsLoading(false);
    }
  }, [user, toast]);

  const getSectionDisplayName = (section: string): string => {
    const sectionNames: Record<string, string> = {
      personalInfo: 'personal information',
      addressInfo: 'address information',
      familyInfo: 'family information',
      professionalLinks: 'professional links',
      education: 'education',
      workExperience: 'work experience',
      certifications: 'certifications',
      skills: 'skills',
      techStack: 'tech stack',
    };
    return sectionNames[section] || 'profile';
  };

  const handleEvaluationComplete = useCallback(() => {
    setEvaluationReady(true);
  }, []);

  const handleCancelEdit = useCallback(() => {
    setEditingSection(null);
    setIsEditingProfile(false);
  }, []);

  // Check if the current user can edit this profile (only their own)
  const canEditProfile = session?.user?.id === user?.id;

  if (!user) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <div className="text-center space-y-3">
          <h2 className="text-xl font-semibold tracking-tight text-foreground">User not found</h2>
          <p className="text-sm text-muted-foreground">The employee you&apos;re looking for doesn&apos;t exist.</p>
          <Button onClick={() => router.push('/dashboard/users')} variant="outline">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Users
          </Button>
        </div>
      </div>
    );
  }

  const getInitials = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').toUpperCase();
  };

  const formatDate = (date: Date | string | null | undefined) => {
    if (!date) return 'Not provided';
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return formatDateUtil(dateObj, { format: 'long' });
  };

  if (!evaluationReady) {
    return (
      <EvaluationLoadingScreen
        userName={user.name}
        durationMs={8000}
        onComplete={handleEvaluationComplete}
      />
    );
  }

  const metaItems: {
    key: string;
    label: string;
    icon: ReactNode;
    value: ReactNode;
  }[] = [
    {
      key: 'employeeId',
      label: 'Employee ID',
      icon: <UserIcon className="h-3.5 w-3.5 text-primary" />,
      value: user.employeeId || 'Not assigned',
    },
    {
      key: 'email',
      label: 'Work Email',
      icon: <Mail className="h-3.5 w-3.5 text-primary" />,
      value: (
        <span className="block truncate" title={user.email}>
          {user.email}
        </span>
      ),
    },
    {
      key: 'phone',
      label: 'Work Phone',
      icon: <Phone className="h-3.5 w-3.5 text-primary" />,
      value: user.phone || 'Not provided',
    },
    {
      key: 'team',
      label: 'Team & Role',
      icon: <Building className="h-3.5 w-3.5 text-primary" />,
      value: (
        <div className="space-y-1.5">
          <p className="truncate">{user.department || user.team}</p>
          <div className="flex flex-wrap gap-1">
            {user.role && USER_ROLES[user.role] && (
              <Badge variant="outline" className={`${getRoleBadgeColor(user.role)} text-[10px] px-1.5 py-0`}>
                {USER_ROLES[user.role]}
              </Badge>
            )}
            {user.joinDate && (() => {
              const empStatus = calculateEmploymentStatus(user.joinDate);
              return empStatus.label ? (
                <Badge
                  variant="outline"
                  className={`${getEmploymentStatusBadgeColor(empStatus.status)} text-[10px] px-1.5 py-0`}
                >
                  {empStatus.label}
                </Badge>
              ) : null;
            })()}
          </div>
        </div>
      ),
    },
    {
      key: 'joinDate',
      label: 'Join Date',
      icon: <Calendar className="h-3.5 w-3.5 text-primary" />,
      value: formatDate(user.joinDate || user.createdAt),
    },
  ];

  if (user.department === 'Production') {
    metaItems.push({
      key: 'techStack',
      label: 'Tech Stack',
      icon: <Laptop className="h-3.5 w-3.5 text-primary" />,
      value: user.techStack ? (
        <Badge
          variant="outline"
          title={user.techStack}
          className="max-w-full truncate whitespace-nowrap leading-4 text-[10px] px-1.5 py-0 bg-primary/10 text-primary border-primary/20"
        >
          {user.techStack}
        </Badge>
      ) : (
        <span className="text-muted-foreground">Not specified</span>
      ),
    });
  }

  if (user.department === 'Design') {
    metaItems.push({
      key: 'designSubTeam',
      label: 'Design Sub-Team',
      icon: <Palette className="h-3.5 w-3.5 text-primary" />,
      value: user.designSubTeam ? (
        <Badge
          variant="outline"
          title={user.designSubTeam}
          className="max-w-full truncate whitespace-nowrap leading-4 text-[10px] px-1.5 py-0 bg-primary/10 text-primary border-primary/20"
        >
          {user.designSubTeam}
        </Badge>
      ) : (
        <span className="text-muted-foreground">
          {isDesignHead(user.position || '') ? 'Not specified (optional for heads)' : 'Not specified'}
        </span>
      ),
    });
  }

  return (
    <motion.div
      className="space-y-6"
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.45, ease: easeOutExpo }}
    >
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-3 min-w-0">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push('/dashboard/users')}
            className="shrink-0 mt-0.5"
            aria-label="Back to users"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <Avatar className="h-14 w-14 shrink-0 border border-border">
            <AvatarFallback className="text-lg font-semibold">
              {getInitials(user.name)}
            </AvatarFallback>
          </Avatar>
          <div className="min-w-0">
            <h1 className="text-2xl font-semibold tracking-tight text-foreground truncate">
              {user.name}
            </h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              {user.position || user.designation}
              {(user.department || user.team) && (
                <>
                  <span className="mx-1.5 text-border">·</span>
                  {user.department || user.team} team
                </>
              )}
            </p>
            {user.manager && (
              <p className="text-xs text-muted-foreground mt-1">
                Reports to{' '}
                <span className="font-medium text-foreground/80">{user.manager.name}</span>
                {user.manager.role ? (
                  <span className="text-muted-foreground"> ({user.manager.role})</span>
                ) : null}
              </p>
            )}
          </div>
        </div>
        {canEditProfile && (
          <Button
            variant="outline"
            size="sm"
            onClick={() => setIsEditingProfile(!isEditingProfile)}
            className="shrink-0"
          >
            <Edit className="h-3.5 w-3.5 mr-1.5" />
            {isEditingProfile ? 'Cancel Edit' : 'Edit Profile'}
          </Button>
        )}
      </div>

      {/* Meta strip */}
      <motion.div
        className="rounded-xl border border-border bg-card overflow-hidden shadow-sm"
        variants={staggerContainer}
        initial="initial"
        animate="animate"
      >
        <div
          className={`grid grid-cols-2 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x divide-border ${
            metaItems.length >= 6 ? 'xl:grid-cols-6' : 'xl:grid-cols-5'
          }`}
        >
          {metaItems.map((item) => (
            <motion.div
              key={item.key}
              variants={staggerItem}
              className="flex min-w-0 items-start gap-2.5 overflow-hidden px-4 py-3.5"
            >
              <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                {item.icon}
              </div>
              <div className="min-w-0 flex-1 overflow-hidden">
                <p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
                  {item.label}
                </p>
                <div className="mt-0.5 min-w-0 overflow-hidden text-sm font-medium text-foreground">
                  {item.value}
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      </motion.div>

      {/* Date range filter */}
      <div className="rounded-xl border border-border bg-card px-4 py-3 shadow-sm">
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground">
            <Calendar className="h-3.5 w-3.5 text-primary" />
            Date range
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <DatePicker
              value={dateFrom}
              onChange={setDateFrom}
              max={dateTo}
              buttonClassName="h-8 w-[148px]"
              title="From date"
            />
            <span className="text-xs text-muted-foreground">to</span>
            <DatePicker
              value={dateTo}
              onChange={setDateTo}
              min={dateFrom}
              buttonClassName="h-8 w-[148px]"
              title="To date"
            />
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 text-xs text-muted-foreground hover:text-foreground"
            onClick={() => {
              setDateFrom(defaultDateFrom());
              setDateTo(new Date().toISOString().split("T")[0]);
            }}
          >
            Reset
          </Button>
          <span className="ml-auto text-xs text-muted-foreground hidden sm:inline">Applies to all tabs</span>
          <UserDetailExportMenu
            user={user}
            dateFrom={dateFrom}
            dateTo={dateTo}
            section="all"
            variant="all"
          />
        </div>
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={handleTabChange} className="space-y-5">
        <div className="rounded-xl border border-border bg-muted/40 p-1.5">
          <TabsList className="grid h-auto w-full grid-cols-2 gap-1 bg-transparent sm:grid-cols-4">
            <TabsTrigger value="report-card" className={TAB_TRIGGER_CLASS}>
              <ClipboardList className="h-4 w-4 shrink-0" />
              <span className="truncate">Report Card</span>
            </TabsTrigger>
            <TabsTrigger value="performance" className={TAB_TRIGGER_CLASS}>
              <TrendingUp className="h-4 w-4 shrink-0" />
              <span className="truncate">Performance</span>
            </TabsTrigger>
            {user.department !== 'Network IT' ? (
              <TabsTrigger value="logged-hours" className={TAB_TRIGGER_CLASS}>
                <Clock className="h-4 w-4 shrink-0" />
                <span className="truncate">Work Summary</span>
              </TabsTrigger>
            ) : (
              <TabsTrigger value="work-history" className={TAB_TRIGGER_CLASS}>
                <ClipboardList className="h-4 w-4 shrink-0" />
                <span className="truncate">Work History</span>
              </TabsTrigger>
            )}
            <TabsTrigger value="attendance" className={TAB_TRIGGER_CLASS}>
              <CalendarCheck className="h-4 w-4 shrink-0" />
              <span className="truncate">Attendance</span>
            </TabsTrigger>
          </TabsList>
        </div>

        <div className="relative overflow-hidden">
          <AnimatedTabsContent
            value="report-card"
            className="space-y-5 mt-0"
            activeTab={activeTab}
            previousTab={previousTab}
            isAnimating={isAnimating}
            animationDirection={animationDirection}
          >
            <div className="flex justify-end">
              <UserDetailExportMenu
                user={user}
                dateFrom={dateFrom}
                dateTo={dateTo}
                section="report-card"
              />
            </div>
            <UserReportCardWrapper
              key={reportCardVisit}
              userId={user.id}
              userName={user.name}
              dateFrom={dateFrom}
              dateTo={dateTo}
              initialData={bootMatchesRange ? reportBoot?.data ?? null : null}
              initialError={bootMatchesRange ? reportBoot?.error ?? null : null}
            />
          </AnimatedTabsContent>

          <AnimatedTabsContent
            value="performance"
            className="space-y-5 mt-0"
            activeTab={activeTab}
            previousTab={previousTab}
            isAnimating={isAnimating}
            animationDirection={animationDirection}
          >
            <div className="flex justify-end">
              <UserDetailExportMenu
                user={user}
                dateFrom={dateFrom}
                dateTo={dateTo}
                section="performance"
              />
            </div>
            <UserPerformance user={user} dateFrom={dateFrom} dateTo={dateTo} />
          </AnimatedTabsContent>

          {user.department !== 'Network IT' && (
            <AnimatedTabsContent
              value="logged-hours"
              className="space-y-5 mt-0"
              activeTab={activeTab}
              previousTab={previousTab}
              isAnimating={isAnimating}
              animationDirection={animationDirection}
            >
              <div className="flex justify-end">
                <UserDetailExportMenu
                  user={user}
                  dateFrom={dateFrom}
                  dateTo={dateTo}
                  section="logged-hours"
                />
              </div>
              <LoggedHoursImport
                userId={user.id}
                userName={user.name}
                onImportComplete={() => {
                  window.dispatchEvent(
                    new CustomEvent('loggedHoursUpdated', {
                      detail: { userId: user.id },
                    })
                  );
                }}
              />
              <UserLoggedHoursViz
                userId={user.id}
                userName={user.name}
                dateFrom={dateFrom}
                dateTo={dateTo}
              />
            </AnimatedTabsContent>
          )}

          {user.department === 'Network IT' && (
            <AnimatedTabsContent
              value="work-history"
              className="space-y-5 mt-0"
              activeTab={activeTab}
              previousTab={previousTab}
              isAnimating={isAnimating}
              animationDirection={animationDirection}
            >
              <div className="flex justify-end">
                <UserDetailExportMenu
                  user={user}
                  dateFrom={dateFrom}
                  dateTo={dateTo}
                  section="work-history"
                />
              </div>
              <ItWorkHistory
                userId={user.id}
                userName={user.name}
                dateFrom={dateFrom}
                dateTo={dateTo}
              />
            </AnimatedTabsContent>
          )}

          <AnimatedTabsContent
            value="attendance"
            className="space-y-5 mt-0"
            activeTab={activeTab}
            previousTab={previousTab}
            isAnimating={isAnimating}
            animationDirection={animationDirection}
          >
            <div className="flex justify-end">
              <UserDetailExportMenu
                user={user}
                dateFrom={dateFrom}
                dateTo={dateTo}
                section="attendance"
              />
            </div>
            <UserAttendance
              userId={user.id}
              userName={user.name}
              isItUser={user.department === 'Network IT'}
              dateFrom={dateFrom}
              dateTo={dateTo}
            />
          </AnimatedTabsContent>
        </div>
      </Tabs>
    </motion.div>
  );
} 