import React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import LocalHospitalIcon from '@mui/icons-material/LocalHospital';
import BeachAccessIcon from '@mui/icons-material/BeachAccess';
import SettingsIcon from '@mui/icons-material/Settings';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { User } from '../../types/shift';
import { getContrastColor } from '../../utils/colorUtils';
import { LoadingState, EmptyState } from '../shared';
import UserAvatar from '../UserAvatar';

// Extended User interface with leave information
interface UserWithLeaveInfo extends User {
  leaveInfo?: {
    type: 'sick' | 'vacation';
    from: string;
    to: string;
    coversEntireWeek: boolean;
  } | null;
}

interface ShiftUsersPanelProps {
  users: UserWithLeaveInfo[];
  filteredUsers: UserWithLeaveInfo[];
  loading: boolean;
  searchTerm: string;
  onSearchChange: (term: string) => void;
  onUserDragStart: (e: React.DragEvent, userId: number, userName: string) => void;
  onUserDragEnd?: () => void;
  selectedRoleFilter: number | 'all';
  hasPlannerAccess?: boolean;
  onUserSettings?: (user: UserWithLeaveInfo) => void;
}

const ShiftUsersPanel: React.FC<ShiftUsersPanelProps> = ({
  users,
  filteredUsers,
  loading,
  searchTerm,
  onSearchChange,
  onUserDragStart,
  onUserDragEnd,
  selectedRoleFilter,
  hasPlannerAccess = false,
  onUserSettings,
}) => {
  const { i18n } = useLingui();

  // Helper function to check if user should be visible (for animations)
  const isUserVisible = (user: UserWithLeaveInfo) => {
    // Filter by role
    if (selectedRoleFilter !== 'all') {
      if (!user.roles?.some((role) => role.role_id === selectedRoleFilter)) {
        return false;
      }
    }

    // Filter by search term
    if (searchTerm.trim()) {
      const search = searchTerm.toLowerCase();
      if (!user.full_name.toLowerCase().includes(search)) {
        return false;
      }
    }

    return true;
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', flex: 1 }}>
      <Box sx={{ p: 2, pb: 0, flexShrink: 0 }}>
        {/* Search Field */}
        <TextField
          fullWidth
          placeholder={i18n._(t`Mitarbeiter suchen...`)}
          variant="outlined"
          size="small"
          value={searchTerm}
          onChange={(e) => onSearchChange(e.target.value)}
          sx={{ mb: 1 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />

        <Typography variant="subtitle2" gutterBottom>
          <Trans>Verfügbare Mitarbeiter</Trans> ({filteredUsers.length})
        </Typography>
      </Box>

      <Box sx={{ flex: 1, overflow: 'auto', p: 2, pt: 0 }}>
        {loading ? (
          <LoadingState size={24} />
        ) : filteredUsers.length === 0 ? (
          <EmptyState
            title={i18n._(t`Keine Mitarbeiter`)}
            message={i18n._(t`Keine Mitarbeiter verfügbar`)}
          />
        ) : (
          <Box display="flex" flexDirection="column" gap={1}>
            {users.map((user) => {
              const hasLeave = user.leaveInfo !== null && user.leaveInfo !== undefined;
              const coversEntireWeek = user.leaveInfo?.coversEntireWeek || false;
              const leaveType = user.leaveInfo?.type;
              const leaveFrom = user.leaveInfo?.from;
              const leaveTo = user.leaveInfo?.to;
              const isVisible = isUserVisible(user);

              return (
                <Box
                  key={user.usr_id}
                  draggable={!coversEntireWeek}
                  onDragStart={(e) => !coversEntireWeek && onUserDragStart(e, user.usr_id, user.full_name)}
                  onDragEnd={() => onUserDragEnd?.()}
                  sx={{
                    p: 1.5,
                    borderRadius: 1,
                    backgroundColor: hasLeave ? (leaveType === 'sick' ? '#ffebee' : '#e8f5e9') : '#f5f5f5',
                    cursor: coversEntireWeek ? 'not-allowed' : 'grab',
                    display: isVisible ? 'flex' : 'none',
                    alignItems: 'flex-start',
                    gap: 1,
                    opacity: isVisible ? (coversEntireWeek ? 0.6 : 1) : 0,
                    transform: isVisible ? 'scale(1)' : 'scale(0.95)',
                    maxHeight: isVisible ? '500px' : '0',
                    overflow: 'hidden',
                    transition: 'opacity 0.5s ease-in-out, transform 0.5s ease-in-out, max-height 0.5s ease-in-out',
                    border: hasLeave ? (leaveType === 'sick' ? '1px solid #ef5350' : '1px solid #66bb6a') : 'none',
                    position: 'relative',
                    pb: hasPlannerAccess && onUserSettings ? 4 : 1.5,
                    '&:active': {
                      cursor: coversEntireWeek ? 'not-allowed' : 'grabbing',
                    },
                    '&:hover': {
                      backgroundColor: coversEntireWeek
                        ? (leaveType === 'sick' ? '#ffebee' : '#e8f5e9')
                        : (hasLeave ? (leaveType === 'sick' ? '#ffcdd2' : '#c8e6c9') : '#e0e0e0'),
                      boxShadow: coversEntireWeek ? 0 : 2,
                    },
                  }}
                >
                  {hasLeave && (
                    <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5 }}>
                      {leaveType === 'sick' ? (
                        <LocalHospitalIcon sx={{ fontSize: 18, color: '#ef5350' }} />
                      ) : (
                        <BeachAccessIcon sx={{ fontSize: 18, color: '#ffa726' }} />
                      )}
                    </Box>
                  )}
                  <UserAvatar
                    photoUrl={user.photourl}
                    initials={user.initials}
                    fullName={user.full_name}
                    sx={{
                      width: 32,
                      height: 32,
                      fontSize: '0.75rem',
                    }}
                  />
                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      <Typography variant="body2" fontWeight="bold" noWrap sx={{ flex: 1 }}>
                        {user.full_name}
                      </Typography>
                      {user.required_hours_per_month && user.required_hours_per_month > 0 && (
                        <Tooltip
                          title={
                            <Box>
                              <Typography variant="caption" display="block">
                                <Trans>Geplant:</Trans> {(user.planned_hours || 0).toFixed(1)}h / {user.required_hours_per_month.toFixed(0)}h
                              </Typography>
                              <Typography variant="caption" display="block">
                                {user.allow_overtime
                                  ? i18n._(t`Überstunden erlaubt`)
                                  : i18n._(t`Überstunden NICHT erlaubt`)}
                              </Typography>
                            </Box>
                          }
                          arrow
                        >
                          <Box
                            sx={{
                              display: 'flex',
                              alignItems: 'center',
                              px: 0.5,
                              py: 0.125,
                              borderRadius: 0.5,
                              backgroundColor: 'rgba(0,0,0,0.06)',
                              fontSize: '0.65rem',
                              fontWeight: 500,
                              color: (() => {
                                const pct = user.required_hours_per_month > 0
                                  ? ((user.planned_hours || 0) / user.required_hours_per_month) * 100
                                  : 0;
                                return pct >= 100 ? '#d32f2f' : pct >= 80 ? '#ff9800' : '#4caf50';
                              })(),
                              whiteSpace: 'nowrap',
                            }}
                          >
                            {(user.planned_hours || 0).toFixed(0)}/{user.required_hours_per_month.toFixed(0)}h
                          </Box>
                        </Tooltip>
                      )}
                    </Box>
                    {hasLeave && (
                      <Typography variant="caption" display="block" sx={{ color: leaveType === 'sick' ? '#d32f2f' : '#f57c00', mt: 0.25 }}>
                        {leaveType === 'sick' ? <Trans>Krank</Trans> : <Trans>Urlaub</Trans>}
                        {!coversEntireWeek && leaveFrom && leaveTo && (
                          <> ({new Date(leaveFrom).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' })} - {new Date(leaveTo).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' })})</>
                        )}
                      </Typography>
                    )}
                    {user.roles && user.roles.length > 0 && (
                      <Box display="flex" gap={0.5} flexWrap="wrap" mt={0.5}>
                        {user.roles.slice(0, 2).map((role) => (
                          <Chip
                            key={role.role_id}
                            label={role.role_name}
                            size="small"
                            sx={{
                              height: 18,
                              fontSize: '0.65rem',
                              backgroundColor: role.role_color,
                              color: getContrastColor(role.role_color),
                            }}
                          />
                        ))}
                        {user.roles.length > 2 && (
                          <Chip
                            label={`+${user.roles.length - 2}`}
                            size="small"
                            sx={{
                              height: 18,
                              fontSize: '0.65rem',
                            }}
                          />
                        )}
                      </Box>
                    )}
                  </Box>

                  {hasPlannerAccess && onUserSettings && (
                    <Tooltip title={i18n._(t`Benutzereinstellungen`)}>
                      <IconButton
                        size="small"
                        onClick={(e) => {
                          e.stopPropagation();
                          e.preventDefault();
                          onUserSettings(user);
                        }}
                        onMouseDown={(e) => e.stopPropagation()}
                        sx={{
                          position: 'absolute',
                          bottom: 4,
                          right: 4,
                          width: 24,
                          height: 24,
                          backgroundColor: 'rgba(255, 255, 255, 0.85)',
                          color: '#666',
                          '&:hover': {
                            backgroundColor: 'rgba(255, 255, 255, 1)',
                            color: '#1976d2',
                            transform: 'scale(1.1)',
                          },
                          transition: 'all 0.2s ease-in-out',
                        }}
                      >
                        <SettingsIcon sx={{ fontSize: 14 }} />
                      </IconButton>
                    </Tooltip>
                  )}
                </Box>
              );
            })}
          </Box>
        )}
      </Box>
    </Box>
  );
};

// Memoize to prevent re-renders when parent state changes but users are the same
export default React.memo(ShiftUsersPanel, (prevProps, nextProps) => {
  return (
    prevProps.filteredUsers.length === nextProps.filteredUsers.length &&
    prevProps.filteredUsers.every((u, i) => u.usr_id === nextProps.filteredUsers[i]?.usr_id) &&
    prevProps.loading === nextProps.loading &&
    prevProps.searchTerm === nextProps.searchTerm &&
    prevProps.hasPlannerAccess === nextProps.hasPlannerAccess
  );
});
