import React, { useState, useEffect, useMemo, useRef } from 'react';
import CircularProgress from '@mui/material/CircularProgress';
import SentimentSatisfiedIcon from '@mui/icons-material/SentimentSatisfied';
import SentimentNeutralIcon from '@mui/icons-material/SentimentNeutral';
import SentimentVeryDissatisfiedIcon from '@mui/icons-material/SentimentVeryDissatisfied';
import { Calendar, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, UserCircle2, Users, Search, Check, X } from 'lucide-react';
import axios from 'axios';
import { Trans } from '@lingui/macro';
import type {
  TeamScheduleResponse,
  ScheduleUser,
  ScheduleDay,
  ScheduleShift,
  ScheduleTeam,
  ShiftTemplateInfo,
} from '../types/departmentSchedule';
import { getContrastColor } from '../utils/colorUtils';
import { handleApiError } from '../utils/errorHandler';
import { computeMergedCells, MergedCell } from '../utils/scheduleMerge';
import CoverageDetailsModal from '../components/CoverageDetailsModal';
import type { DayCoverageAnalysis } from '../components/DayCoverageIndicator';

const GERMAN_MONTHS = [
  'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
  'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember',
];

const DAY_SHORT_NAMES: Record<string, string> = {
  Monday: 'Mo',
  Tuesday: 'Di',
  Wednesday: 'Mi',
  Thursday: 'Do',
  Friday: 'Fr',
  Saturday: 'Sa',
  Sunday: 'So',
};

const CELL_WIDTH = 80;
const EMPLOYEE_COL_WIDTH = 220;

interface TeamGroup {
  id: string;
  name: string;
  color: string;
  memberIds: number[];
  isUnassigned: boolean;
}

const getUrlParam = (key: string): string | null => {
  const params = new URLSearchParams(window.location.search);
  return params.get(key);
};

const setUrlParam = (key: string, value: string | number): void => {
  const params = new URLSearchParams(window.location.search);
  params.set(key, String(value));
  const newUrl = `${window.location.pathname}?${params.toString()}${window.location.hash}`;
  window.history.replaceState(null, '', newUrl);
};

export const TeamScheduleTab: React.FC = () => {
  const now = new Date();
  const [currentMonth, setCurrentMonth] = useState<number>(() => {
    const urlMonth = getUrlParam('ts_month');
    return urlMonth ? parseInt(urlMonth, 10) : now.getMonth() + 1;
  });
  const [currentYear, setCurrentYear] = useState<number>(() => {
    const urlYear = getUrlParam('ts_year');
    return urlYear ? parseInt(urlYear, 10) : now.getFullYear();
  });
  const [scheduleData, setScheduleData] = useState<TeamScheduleResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isLegendOpen, setIsLegendOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTeamFilter, setSelectedTeamFilter] = useState<string>('all');
  const [teamDropdownOpen, setTeamDropdownOpen] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [hoveredPending, setHoveredPending] = useState<string | null>(null);
  const teamDropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (teamDropdownRef.current && !teamDropdownRef.current.contains(e.target as Node)) {
        setTeamDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);
  const [coverageData, setCoverageData] = useState<Record<string, any>>({});
  const [coverageDetailsOpen, setCoverageDetailsOpen] = useState(false);
  const [selectedCoverage, setSelectedCoverage] = useState<DayCoverageAnalysis | null>(null);

  const currentMonthName = `${GERMAN_MONTHS[currentMonth - 1]} ${currentYear}`;

  // Flatten all days from the week-based schedule into a single array for the month
  const allDays: ScheduleDay[] = useMemo(() => {
    if (!scheduleData) return [];
    const days: ScheduleDay[] = [];
    const seen = new Set<string>();
    scheduleData.schedule.forEach((week) => {
      week.days.forEach((day) => {
        if (!seen.has(day.date)) {
          const [y, m] = day.date.split('-').map(Number);
          if (y === currentYear && m === currentMonth) {
            seen.add(day.date);
            days.push(day);
          }
        }
      });
    });
    days.sort((a, b) => a.date.localeCompare(b.date));
    return days;
  }, [scheduleData, currentYear, currentMonth]);

  // Build user lookup map
  const usersMap = useMemo(() => {
    if (!scheduleData) return new Map<number, ScheduleUser>();
    const map = new Map<number, ScheduleUser>();
    scheduleData.users.forEach((u) => map.set(u.usr_id, u));
    return map;
  }, [scheduleData]);

  // Build team groups from API data
  const teamGroups: TeamGroup[] = useMemo(() => {
    if (!scheduleData) return [];

    const groups: TeamGroup[] = scheduleData.teams.map((team) => ({
      id: `team-${team.team_id}`,
      name: team.team_name,
      color: team.team_color,
      memberIds: team.member_ids,
      isUnassigned: false,
    }));

    if (scheduleData.unassigned_user_ids.length > 0) {
      groups.push({
        id: 'team-unassigned',
        name: 'Nicht zugewiesen',
        color: '#6B7280',
        memberIds: scheduleData.unassigned_user_ids,
        isUnassigned: true,
      });
    }

    return groups;
  }, [scheduleData]);

  // Sort members within each group based on search query
  const sortedTeamGroups = useMemo(() => {
    const query = searchQuery.trim().toLowerCase();
    if (!query) return teamGroups;

    return teamGroups.map((group) => {
      const sorted = [...group.memberIds].sort((a, b) => {
        const userA = usersMap.get(a);
        const userB = usersMap.get(b);
        if (!userA || !userB) return 0;
        const nameA = userA.name.toLowerCase();
        const nameB = userB.name.toLowerCase();
        const matchA = nameA.includes(query);
        const matchB = nameB.includes(query);
        if (matchA && !matchB) return -1;
        if (!matchA && matchB) return 1;
        return nameA.localeCompare(nameB);
      });
      return { ...group, memberIds: sorted };
    });
  }, [teamGroups, searchQuery, usersMap]);

  const filteredTeamGroups = useMemo(() => {
    if (selectedTeamFilter === 'all') return sortedTeamGroups;
    return sortedTeamGroups.filter((group) => group.id === selectedTeamFilter);
  }, [sortedTeamGroups, selectedTeamFilter]);

  const shiftTemplates = useMemo(() => {
    if (!scheduleData) return [];
    return scheduleData.shift_templates_used || [];
  }, [scheduleData]);

  // Fetch schedule when month changes
  useEffect(() => {
    fetchSchedule();
  }, [currentMonth, currentYear]);

  const fetchSchedule = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await axios.get('/zeiterfassung/team-schedule', {
        params: {
          month: currentMonth,
          year: currentYear,
        },
      });

      setScheduleData(response.data);

      // Load coverage data for all dates
      const allDates: string[] = [];
      response.data.schedule.forEach((week: any) => {
        week.days.forEach((day: any) => {
          allDates.push(day.date);
        });
      });

      if (allDates.length > 0) {
        loadBulkCoverage(allDates);
      }
    } catch (err: any) {
      setError(handleApiError('TeamScheduleTab.fetchSchedule', err));
    } finally {
      setLoading(false);
    }
  };

  const loadBulkCoverage = async (dates: string[]) => {
    try {
      const response = await axios.post('/zeiterfassung/coverage/analyze-bulk', {
        dates,
      });
      setCoverageData(response.data);
    } catch (err: any) {
      handleApiError('TeamScheduleTab.loadBulkCoverage', err);
    }
  };

  const handlePrevMonth = () => {
    const newMonth = currentMonth === 1 ? 12 : currentMonth - 1;
    const newYear = currentMonth === 1 ? currentYear - 1 : currentYear;
    setCurrentMonth(newMonth);
    setCurrentYear(newYear);
    setUrlParam('ts_month', newMonth);
    setUrlParam('ts_year', newYear);
  };

  const handleNextMonth = () => {
    const newMonth = currentMonth === 12 ? 1 : currentMonth + 1;
    const newYear = currentMonth === 12 ? currentYear + 1 : currentYear;
    setCurrentMonth(newMonth);
    setCurrentYear(newYear);
    setUrlParam('ts_month', newMonth);
    setUrlParam('ts_year', newYear);
  };

  const handleToday = () => {
    const today = new Date();
    const m = today.getMonth() + 1;
    const y = today.getFullYear();
    setCurrentMonth(m);
    setCurrentYear(y);
    setUrlParam('ts_month', m);
    setUrlParam('ts_year', y);
  };

  const isDateToday = (dateStr: string): boolean => {
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    return dateStr === todayStr;
  };

  const isWeekendDay = (dayName: string): boolean => {
    return dayName === 'Saturday' || dayName === 'Sunday';
  };

  const pendingCount = useMemo(() => {
    if (!allDays.length) return 0;
    const seen = new Set<string>();
    allDays.forEach((day) => {
      day.users_data.forEach((ud) => {
        if (ud.vacation?.status === 'submitted') seen.add(`v-${ud.vacation.zvr_id}`);
        if (ud.sick_leave?.status === 'submitted') seen.add(`s-${ud.sick_leave.zsr_id}`);
      });
    });
    return seen.size;
  }, [allDays]);

  const handleApprove = async (type: 'vacation' | 'sick', id: number) => {
    const url = type === 'vacation'
      ? `/zeiterfassung/vacation-requests/${id}/approve`
      : `/zeiterfassung/sick-requests/${id}/approve`;
    setActionLoading(`${type}-${id}`);
    try {
      await axios.patch(url);
      fetchSchedule();
    } catch (e) {
      handleApiError(e);
    } finally {
      setActionLoading(null);
      setHoveredPending(null);
    }
  };

  const handleReject = async (type: 'vacation' | 'sick', id: number) => {
    const url = type === 'vacation'
      ? `/zeiterfassung/vacation-requests/${id}/reject`
      : `/zeiterfassung/sick-requests/${id}/reject`;
    setActionLoading(`${type}-${id}`);
    try {
      await axios.patch(url);
      fetchSchedule();
    } catch (e) {
      handleApiError(e);
    } finally {
      setActionLoading(null);
      setHoveredPending(null);
    }
  };

  const formatTime = (time: string): string => time.substring(0, 5);

  const handleShowCoverageDetails = (coverage: DayCoverageAnalysis) => {
    setSelectedCoverage(coverage);
    setCoverageDetailsOpen(true);
  };

  const getCoverageIcon = (date: string) => {
    const coverage = coverageData[date];
    if (!coverage) return null;
    if (coverage.status === 'neutral') return null;

    const statusIcons: Record<string, { Icon: typeof SentimentSatisfiedIcon; color: string }> = {
      perfect: { Icon: SentimentSatisfiedIcon, color: '#4caf50' },
      good: { Icon: SentimentNeutralIcon, color: '#ff9800' },
      warning: { Icon: SentimentNeutralIcon, color: '#ff9800' },
      critical: { Icon: SentimentVeryDissatisfiedIcon, color: '#f44336' },
    };

    const entry = statusIcons[coverage.status];
    if (!entry) return null;
    const { Icon, color } = entry;

    return (
      <Icon
        onClick={() => handleShowCoverageDetails(coverage)}
        sx={{
          fontSize: '1.2rem',
          cursor: 'pointer',
          color,
          transition: 'transform 0.2s',
          '&:hover': { transform: 'scale(1.2)' },
        }}
      />
    );
  };

  const renderEmployeeCells = (employee: ScheduleUser) => {
    const merged = computeMergedCells(employee.usr_id, allDays);

    return merged.map((cell) => {
      const isToday = isDateToday(cell.date);
      const width = cell.span * CELL_WIDTH;

      if (cell.type === 'vacation') {
        const isPending = cell.vacationStatus === 'submitted';
        const hoverKey = `vacation-${cell.vacationId}`;
        const isHovered = hoveredPending === hoverKey;
        const isLoading = actionLoading === `vacation-${cell.vacationId}`;

        return (
          <div
            key={cell.date}
            style={{ width: `${width}px` }}
            className="tw-h-[60px] tw-flex-none tw-border-r tw-border-b tw-relative tw-bg-white"
            onMouseEnter={() => isPending && setHoveredPending(hoverKey)}
            onMouseLeave={() => isPending && setHoveredPending(null)}
          >
            <div className="tw-p-1 tw-h-full tw-w-full">
              <div
                className={`tw-text-white tw-text-xs tw-rounded-md tw-flex tw-flex-col tw-items-center tw-justify-center tw-h-full tw-w-full tw-shadow-sm tw-transition-all hover:tw-brightness-95 hover:tw-scale-[0.98] tw-relative tw-overflow-hidden ${
                  isPending ? '' : 'tw-bg-blue-500'
                }`}
                style={isPending ? {
                  background: 'repeating-linear-gradient(-45deg, #3b82f6, #3b82f6 4px, #60a5fa 4px, #60a5fa 8px)',
                } : undefined}
              >
                <span className="tw-font-medium tw-text-center tw-truncate tw-w-full tw-px-1">
                  <Trans>Urlaub</Trans>
                </span>
                <span className="tw-text-[9px] tw-mt-0.5 tw-opacity-80">
                  {isPending ? <Trans>Beantragt</Trans> : cell.span > 1 ? <>{cell.span} <Trans>Tage</Trans></> : null}
                </span>
              </div>
            </div>
            {isPending && isHovered && (
              <div className="tw-absolute tw-inset-0 tw-z-30 tw-flex tw-items-center tw-justify-center tw-bg-black/40 tw-rounded-md tw-backdrop-blur-[2px]">
                <div className="tw-flex tw-gap-2">
                  <button
                    type="button"
                    disabled={isLoading}
                    onClick={() => handleApprove('vacation', cell.vacationId!)}
                    className="tw-w-8 tw-h-8 tw-rounded-full tw-bg-green-500 tw-text-white tw-flex tw-items-center tw-justify-center tw-border-0 tw-cursor-pointer hover:tw-bg-green-600 tw-transition-colors tw-shadow-lg disabled:tw-opacity-50"
                  >
                    <Check className="tw-w-4 tw-h-4" />
                  </button>
                  <button
                    type="button"
                    disabled={isLoading}
                    onClick={() => handleReject('vacation', cell.vacationId!)}
                    className="tw-w-8 tw-h-8 tw-rounded-full tw-bg-red-500 tw-text-white tw-flex tw-items-center tw-justify-center tw-border-0 tw-cursor-pointer hover:tw-bg-red-600 tw-transition-colors tw-shadow-lg disabled:tw-opacity-50"
                  >
                    <X className="tw-w-4 tw-h-4" />
                  </button>
                </div>
              </div>
            )}
            {isToday && <div className="tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-0.5 tw-bg-blue-500 tw-z-10"></div>}
          </div>
        );
      }

      if (cell.type === 'sick') {
        const isPending = cell.sickStatus === 'submitted';
        const hoverKey = `sick-${cell.sickId}`;
        const isHovered = hoveredPending === hoverKey;
        const isLoading = actionLoading === `sick-${cell.sickId}`;

        return (
          <div
            key={cell.date}
            style={{ width: `${width}px` }}
            className="tw-h-[60px] tw-flex-none tw-border-r tw-border-b tw-relative tw-bg-white"
            onMouseEnter={() => isPending && setHoveredPending(hoverKey)}
            onMouseLeave={() => isPending && setHoveredPending(null)}
          >
            <div className="tw-p-1 tw-h-full tw-w-full">
              <div
                className={`tw-text-white tw-text-xs tw-rounded-md tw-flex tw-flex-col tw-items-center tw-justify-center tw-h-full tw-w-full tw-shadow-sm tw-transition-all hover:tw-brightness-95 hover:tw-scale-[0.98] tw-relative tw-overflow-hidden ${
                  isPending ? '' : 'tw-bg-red-500'
                }`}
                style={isPending ? {
                  background: 'repeating-linear-gradient(-45deg, #ef4444, #ef4444 4px, #f87171 4px, #f87171 8px)',
                } : undefined}
              >
                <span className="tw-font-medium tw-text-center tw-truncate tw-w-full tw-px-1">
                  <Trans>Krank</Trans>
                </span>
                <span className="tw-text-[9px] tw-mt-0.5 tw-opacity-80">
                  {isPending ? <Trans>Beantragt</Trans> : cell.span > 1 ? <>{cell.span} <Trans>Tage</Trans></> : null}
                </span>
              </div>
            </div>
            {isPending && isHovered && (
              <div className="tw-absolute tw-inset-0 tw-z-30 tw-flex tw-items-center tw-justify-center tw-bg-black/40 tw-rounded-md tw-backdrop-blur-[2px]">
                <div className="tw-flex tw-gap-2">
                  <button
                    type="button"
                    disabled={isLoading}
                    onClick={() => handleApprove('sick', cell.sickId!)}
                    className="tw-w-8 tw-h-8 tw-rounded-full tw-bg-green-500 tw-text-white tw-flex tw-items-center tw-justify-center tw-border-0 tw-cursor-pointer hover:tw-bg-green-600 tw-transition-colors tw-shadow-lg disabled:tw-opacity-50"
                  >
                    <Check className="tw-w-4 tw-h-4" />
                  </button>
                </div>
              </div>
            )}
            {isToday && <div className="tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-0.5 tw-bg-blue-500 tw-z-10"></div>}
          </div>
        );
      }

      if (cell.type === 'shift' && cell.shifts && cell.shifts.length > 0) {
        const shift = cell.shifts[0];
        const bgColor = shift.color || '#9e9e9e';
        const textColor = getContrastColor(bgColor);

        return (
          <div
            key={cell.date}
            style={{ width: `${CELL_WIDTH}px` }}
            className={`tw-h-[60px] tw-flex-none tw-border-r tw-border-b tw-relative tw-bg-white ${isToday ? 'tw-bg-blue-50/30' : ''}`}
          >
            <div className="tw-p-1 tw-h-full tw-w-full">
              <div
                style={{ backgroundColor: bgColor, color: textColor }}
                className="tw-text-xs tw-rounded-md tw-flex tw-flex-col tw-items-center tw-justify-center tw-h-full tw-w-full tw-shadow-sm tw-transition-all hover:tw-brightness-95 hover:tw-scale-[0.98]"
              >
                <span className="tw-text-[10px] tw-font-medium tw-tracking-tight tw-whitespace-nowrap">
                  {formatTime(shift.start_time)}-{formatTime(shift.end_time)}
                </span>
                {shift.role && (
                  <span className="tw-text-[9px] tw-mt-0.5 tw-opacity-80 tw-truncate tw-w-full tw-text-center tw-px-0.5">
                    {shift.role.zr_name}
                  </span>
                )}
              </div>
            </div>
            {isToday && <div className="tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-0.5 tw-bg-blue-500 tw-z-10"></div>}
          </div>
        );
      }

      // Free / empty cell
      return (
        <div
          key={cell.date}
          style={{ width: `${CELL_WIDTH}px` }}
          className={`tw-h-[60px] tw-flex-none tw-border-r tw-border-b tw-relative ${cell.isWeekend ? 'tw-bg-gray-50/80' : 'tw-bg-white'} ${isToday ? 'tw-bg-blue-50/30' : ''}`}
        >
          {isToday && <div className="tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-0.5 tw-bg-blue-500 tw-z-10"></div>}
        </div>
      );
    });
  };

  const getTeamHeaderBg = (group: TeamGroup): string => {
    if (group.isUnassigned) return 'tw-bg-gray-100 tw-text-gray-600';
    // Use the team color as a subtle background tint
    return 'tw-text-gray-800';
  };

  return (
    <div className="tw-p-2 tw-bg-gray-50 tw-flex tw-flex-col tw-flex-1 tw-min-h-0 tw-w-full">
      <div className="tw-w-full">
        {/* Header Area */}
        <div className="tw-flex tw-flex-col md:tw-flex-row md:tw-items-center tw-justify-between tw-gap-4 tw-mb-6">
          <div>
            <div className="tw-flex tw-items-center tw-gap-3">
              <h1 className="tw-text-2xl md:tw-text-3xl tw-font-bold tw-text-gray-900 tw-m-0">
                <Trans>Teamplan</Trans>
              </h1>
              {pendingCount > 0 && (
                <span className="tw-relative tw-flex tw-items-center tw-gap-1.5 tw-bg-amber-50 tw-border tw-border-amber-200 tw-rounded-full tw-px-2.5 tw-py-1">
                  <span className="tw-relative tw-flex tw-h-2.5 tw-w-2.5">
                    <span className="tw-animate-ping tw-absolute tw-inline-flex tw-h-full tw-w-full tw-rounded-full tw-bg-amber-400 tw-opacity-75"></span>
                    <span className="tw-relative tw-inline-flex tw-rounded-full tw-h-2.5 tw-w-2.5 tw-bg-amber-500"></span>
                  </span>
                  <span className="tw-text-xs tw-font-semibold tw-text-amber-700">
                    {pendingCount} <Trans>offen</Trans>
                  </span>
                </span>
              )}
            </div>
            <p className="tw-text-gray-500 tw-mt-1 tw-text-sm tw-m-0">
              <Trans>Schichten und Abwesenheiten verwalten</Trans>
            </p>
          </div>

          {/* Month Navigation */}
          <div className="tw-flex tw-items-center tw-gap-2 tw-bg-white tw-p-1 tw-rounded-lg tw-border tw-shadow-sm tw-self-start md:tw-self-auto">
            <button
              onClick={handlePrevMonth}
              className="tw-p-2 tw-rounded-md hover:tw-bg-gray-100 tw-transition-colors tw-border-0 tw-bg-transparent tw-cursor-pointer"
            >
              <ChevronLeft className="tw-w-5 tw-h-5 tw-text-gray-600" />
            </button>
            <div className="tw-flex tw-items-center tw-gap-2 tw-px-4 tw-min-w-[180px] tw-justify-center tw-font-semibold tw-text-gray-700">
              <Calendar className="tw-w-4 tw-h-4 tw-text-gray-400" />
              <span>{currentMonthName}</span>
            </div>
            <button
              onClick={handleNextMonth}
              className="tw-p-2 tw-rounded-md hover:tw-bg-gray-100 tw-transition-colors tw-border-0 tw-bg-transparent tw-cursor-pointer"
            >
              <ChevronRight className="tw-w-5 tw-h-5 tw-text-gray-600" />
            </button>
            <div className="tw-h-6 tw-w-px tw-bg-gray-200 tw-mx-1"></div>
            <button
              onClick={handleToday}
              className="tw-text-xs tw-px-2 tw-h-8 tw-rounded-md hover:tw-bg-gray-100 tw-transition-colors tw-border-0 tw-bg-transparent tw-cursor-pointer tw-font-medium tw-text-gray-600"
            >
              <Trans>Heute</Trans>
            </button>
          </div>
        </div>

        {/* Controls Bar */}
        <div className="tw-mb-6 tw-shadow-sm tw-border tw-border-gray-200 tw-rounded-xl tw-bg-white">
          <div className="tw-p-4">
            <div className="tw-flex tw-flex-col md:tw-flex-row tw-gap-4 tw-justify-between tw-items-start md:tw-items-center">
              {/* Search & Team Filter */}
              <div className="tw-flex tw-items-center tw-gap-3 tw-w-full md:tw-w-auto">
                <div className="tw-relative tw-w-full md:tw-w-[280px]">
                  <Search className="tw-absolute tw-left-3 tw-top-1/2 tw--translate-y-1/2 tw-w-4 tw-h-4 tw-text-gray-400 tw-pointer-events-none" />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Mitarbeiter suchen..."
                    className="tw-w-full tw-h-10 tw-pl-9 tw-pr-3 tw-rounded-md tw-border tw-border-gray-300 tw-bg-white tw-text-sm tw-text-gray-700 focus:tw-outline-none focus:tw-ring-2 focus:tw-ring-blue-500 focus:tw-border-blue-500"
                  />
                </div>
                {teamGroups.length > 1 && (
                  <div className="tw-relative" ref={teamDropdownRef}>
                    <button
                      type="button"
                      onClick={() => setTeamDropdownOpen(!teamDropdownOpen)}
                      className="tw-flex tw-items-center tw-gap-2 tw-h-10 tw-px-3 tw-rounded-md tw-border tw-border-gray-300 tw-bg-white tw-text-sm tw-text-gray-700 hover:tw-border-gray-400 focus:tw-outline-none focus:tw-ring-2 focus:tw-ring-blue-500 focus:tw-border-blue-500 tw-cursor-pointer tw-min-w-[180px] tw-transition-colors"
                    >
                      <Users className="tw-w-4 tw-h-4 tw-text-gray-400 tw-flex-shrink-0" />
                      {selectedTeamFilter === 'all' ? (
                        <span className="tw-flex-1 tw-text-left"><Trans>Alle Teams</Trans></span>
                      ) : (
                        <span className="tw-flex tw-items-center tw-gap-2 tw-flex-1 tw-text-left">
                          <span
                            className="tw-w-2.5 tw-h-2.5 tw-rounded-full tw-flex-shrink-0"
                            style={{ backgroundColor: teamGroups.find((g) => g.id === selectedTeamFilter)?.color || '#6B7280' }}
                          />
                          {teamGroups.find((g) => g.id === selectedTeamFilter)?.name}
                        </span>
                      )}
                      <ChevronDown className={`tw-w-4 tw-h-4 tw-text-gray-400 tw-flex-shrink-0 tw-transition-transform ${teamDropdownOpen ? 'tw-rotate-180' : ''}`} />
                    </button>
                    {teamDropdownOpen && (
                      <div className="tw-absolute tw-z-50 tw-mt-1 tw-w-full tw-min-w-[200px] tw-bg-white tw-border tw-border-gray-200 tw-rounded-lg tw-shadow-lg tw-py-1 tw-max-h-[280px] tw-overflow-y-auto">
                        <button
                          type="button"
                          onClick={() => { setSelectedTeamFilter('all'); setTeamDropdownOpen(false); }}
                          className={`tw-flex tw-items-center tw-gap-2.5 tw-w-full tw-px-3 tw-py-2 tw-text-sm tw-text-left tw-border-0 tw-cursor-pointer tw-transition-colors ${
                            selectedTeamFilter === 'all'
                              ? 'tw-bg-blue-50 tw-text-blue-700 tw-font-medium'
                              : 'tw-bg-transparent tw-text-gray-700 hover:tw-bg-gray-50'
                          }`}
                        >
                          <Users className="tw-w-4 tw-h-4 tw-text-gray-400" />
                          <Trans>Alle Teams</Trans>
                        </button>
                        {teamGroups.map((group) => (
                          <button
                            key={group.id}
                            type="button"
                            onClick={() => { setSelectedTeamFilter(group.id); setTeamDropdownOpen(false); }}
                            className={`tw-flex tw-items-center tw-gap-2.5 tw-w-full tw-px-3 tw-py-2 tw-text-sm tw-text-left tw-border-0 tw-cursor-pointer tw-transition-colors ${
                              selectedTeamFilter === group.id
                                ? 'tw-bg-blue-50 tw-text-blue-700 tw-font-medium'
                                : 'tw-bg-transparent tw-text-gray-700 hover:tw-bg-gray-50'
                            }`}
                          >
                            <span
                              className="tw-w-3 tw-h-3 tw-rounded-full tw-flex-shrink-0 tw-shadow-sm"
                              style={{ backgroundColor: group.color }}
                            />
                            {group.name}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>

              <button
                onClick={() => setIsLegendOpen(!isLegendOpen)}
                className="tw-flex tw-items-center tw-gap-2 tw-text-sm tw-text-gray-600 hover:tw-text-gray-900 tw-transition-colors tw-py-1 tw-px-3 hover:tw-bg-gray-100 tw-rounded-md tw-border-0 tw-bg-transparent tw-cursor-pointer"
              >
                <span className="tw-font-medium"><Trans>Legende</Trans></span>
                {isLegendOpen ? <ChevronUp className="tw-w-4 tw-h-4" /> : <ChevronDown className="tw-w-4 tw-h-4" />}
              </button>
            </div>

            {/* Collapsible Legend */}
            {isLegendOpen && (
              <div className="tw-mt-4 tw-pt-4 tw-border-t tw-grid tw-grid-cols-2 md:tw-grid-cols-4 lg:tw-grid-cols-7 tw-gap-3">
                <div className="tw-flex tw-items-center tw-gap-2">
                  <div className="tw-w-3 tw-h-3 tw-rounded tw-bg-blue-500 tw-shadow-sm"></div>
                  <span className="tw-text-xs tw-text-gray-600"><Trans>Urlaub</Trans></span>
                </div>
                <div className="tw-flex tw-items-center tw-gap-2">
                  <div className="tw-w-3 tw-h-3 tw-rounded tw-bg-red-500 tw-shadow-sm"></div>
                  <span className="tw-text-xs tw-text-gray-600"><Trans>Krank</Trans></span>
                </div>
                <div className="tw-flex tw-items-center tw-gap-2">
                  <div className="tw-w-3 tw-h-3 tw-rounded tw-bg-gray-300 tw-shadow-sm"></div>
                  <span className="tw-text-xs tw-text-gray-600"><Trans>Frei</Trans></span>
                </div>
                {shiftTemplates.map((template) => (
                  <div key={template.zst_id} className="tw-flex tw-items-center tw-gap-2">
                    <div
                      className="tw-w-3 tw-h-3 tw-rounded tw-shadow-sm"
                      style={{ backgroundColor: template.zst_color }}
                    ></div>
                    <span className="tw-text-xs tw-font-medium tw-text-gray-700">{template.zst_name}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Loading State */}
        {loading && (
          <div className="tw-flex tw-items-center tw-justify-center tw-py-20">
            <CircularProgress />
          </div>
        )}

        {/* Error State */}
        {error && (
          <div className="tw-bg-red-50 tw-border tw-border-red-200 tw-rounded-lg tw-p-4 tw-mb-6 tw-text-red-700 tw-text-sm">
            {error}
          </div>
        )}

        {/* Empty State */}
        {!loading && !error && allDays.length === 0 && scheduleData && (
          <div className="tw-py-20 tw-text-center tw-text-gray-500 tw-bg-white tw-rounded-xl tw-border tw-shadow-sm">
            <UserCircle2 className="tw-w-12 tw-h-12 tw-mx-auto tw-text-gray-300 tw-mb-3" />
            <p><Trans>Keine Plandaten gefunden</Trans></p>
          </div>
        )}

        {/* Schedule Grid */}
        {!loading && !error && allDays.length > 0 && (
          <div className="tw-bg-white tw-rounded-xl tw-shadow-sm tw-border tw-border-gray-200 tw-overflow-hidden tw-flex tw-flex-col tw-flex-1 tw-min-h-0" style={{ minHeight: '400px' }}>
            {/* Scrollable Container */}
            <div className="tw-overflow-auto tw-flex-1 tw-relative custom-scrollbar">
              <div style={{ minWidth: 'max-content' }}>

                {/* Sticky Header Row */}
                <div className="tw-sticky tw-top-0 tw-z-20 tw-flex tw-bg-white tw-shadow-sm tw-border-b">
                  {/* Top Left Corner - Double Sticky */}
                  <div
                    className="tw-sticky tw-left-0 tw-z-30 tw-bg-white tw-border-r tw-p-4 tw-font-bold tw-text-gray-800 tw-flex-none tw-flex tw-items-center"
                    style={{ width: `${EMPLOYEE_COL_WIDTH}px`, boxShadow: '2px 0 5px -2px rgba(0,0,0,0.1)' }}
                  >
                    <Trans>Mitarbeiter</Trans>
                  </div>

                  {/* Date Columns */}
                  <div className="tw-flex">
                    {allDays.map((day) => {
                      const dayNum = parseInt(day.date.split('-')[2], 10);
                      const dayName = DAY_SHORT_NAMES[day.day_name] || day.day_name;
                      const isWeekend = isWeekendDay(day.day_name);
                      const isToday = isDateToday(day.date);

                      return (
                        <div
                          key={day.date}
                          style={{ width: `${CELL_WIDTH}px` }}
                          className={`tw-flex-none tw-text-center tw-py-3 tw-border-r tw-group ${isWeekend ? 'tw-bg-gray-50/70' : 'tw-bg-white'} ${isToday ? 'tw-bg-blue-50/50' : ''}`}
                        >
                          <div className={`tw-text-[10px] tw-uppercase tw-font-bold tw-mb-1 ${isToday ? 'tw-text-blue-600' : 'tw-text-gray-500'}`}>
                            {dayName}
                          </div>
                          <div className={`tw-text-sm tw-font-bold tw-w-7 tw-h-7 tw-mx-auto tw-flex tw-items-center tw-justify-center tw-rounded-full ${isToday ? 'tw-bg-blue-600 tw-text-white tw-shadow-md' : 'tw-text-gray-900'}`}>
                            {dayNum}
                          </div>
                          {/* Coverage icon */}
                          <div className="tw-mt-1 tw-flex tw-justify-center tw-h-5">
                            {getCoverageIcon(day.date)}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* Team Groups */}
                <div className="tw-divide-y tw-divide-gray-100">
                  {filteredTeamGroups.map((group) => {
                    const GroupIcon = group.isUnassigned ? Users : UserCircle2;
                    const members = group.memberIds
                      .map((id) => usersMap.get(id))
                      .filter((u): u is ScheduleUser => !!u);

                    if (members.length === 0) return null;

                    return (
                      <div key={group.id} className="tw-border-b-[8px] tw-border-gray-100 last:tw-border-0">
                        {/* Team Header Row */}
                        <div
                          className={`tw-sticky tw-left-0 tw-z-10 tw-border-b tw-px-4 tw-py-3 tw-font-semibold tw-text-xs tw-uppercase tw-tracking-wider tw-flex tw-items-center tw-justify-between tw-shadow-sm ${getTeamHeaderBg(group)}`}
                          style={!group.isUnassigned ? { backgroundColor: `${group.color}15` } : undefined}
                        >
                          <div className="tw-flex tw-items-center tw-gap-2">
                            <GroupIcon className="tw-w-4 tw-h-4" style={!group.isUnassigned ? { color: group.color } : undefined} />
                            <span style={!group.isUnassigned ? { color: group.color } : undefined}>{group.name}</span>
                          </div>
                          <span className="tw-text-[10px] tw-font-medium tw-opacity-70 tw-border tw-px-1.5 tw-py-0.5 tw-rounded tw-bg-white/50">
                            {members.length} <Trans>Mitarbeiter</Trans>
                          </span>
                        </div>

                        {/* Employee Rows */}
                        {members.map((employee) => (
                          <div
                            key={`${group.id}-${employee.usr_id}`}
                            className="tw-flex hover:tw-bg-gray-50/50 tw-transition-colors tw-group/row"
                          >
                            {/* Employee Info - Sticky Left */}
                            <div
                              className="tw-sticky tw-left-0 tw-z-10 tw-bg-white group-hover/row:tw-bg-gray-50 tw-transition-colors tw-border-r tw-flex-none tw-p-3 tw-flex tw-flex-col tw-justify-center"
                              style={{ width: `${EMPLOYEE_COL_WIDTH}px`, boxShadow: '2px 0 5px -2px rgba(0,0,0,0.05)' }}
                            >
                              <div className="tw-font-semibold tw-text-sm tw-text-gray-900">{employee.name}</div>
                              <div className="tw-text-xs tw-text-gray-500 tw-mt-0.5">
                                {employee.roles.map((r) => r.zr_name).join(', ')}
                              </div>
                            </div>

                            {/* Shift Cells */}
                            <div className="tw-flex">
                              {renderEmployeeCells(employee)}
                            </div>
                          </div>
                        ))}
                      </div>
                    );
                  })}
                </div>

                {filteredTeamGroups.length === 0 && !loading && (
                  <div className="tw-py-20 tw-text-center tw-text-gray-500 tw-bg-gray-50/50">
                    <UserCircle2 className="tw-w-12 tw-h-12 tw-mx-auto tw-text-gray-300 tw-mb-3" />
                    <p><Trans>Keine Mitarbeiter gefunden</Trans></p>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Coverage Details Modal */}
      <CoverageDetailsModal
        open={coverageDetailsOpen}
        onClose={() => setCoverageDetailsOpen(false)}
        coverage={selectedCoverage}
      />
    </div>
  );
};
