import React, { useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import AddIcon from '@mui/icons-material/Add';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import type { ClassInstructorPriority } from '../../types/class';
import type { User } from '../../types/shift';

interface InstructorPriorityPickerProps {
  users: User[];
  priorities: ClassInstructorPriority[];
  onChange: (priorities: ClassInstructorPriority[]) => void;
  error?: string;
}

const normalize = (list: ClassInstructorPriority[]): ClassInstructorPriority[] =>
  list.map((item, index) => ({ ...item, zctip_priority: index + 1 }));

const InstructorPriorityPicker: React.FC<InstructorPriorityPickerProps> = ({
  users,
  priorities,
  onChange,
  error,
}) => {
  const { i18n } = useLingui();
  const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);

  const existingIds: Set<number> = new Set(priorities.map((p) => p.zctip_user_id));
  const available: User[] = users.filter((u) => !existingIds.has(u.usr_id));

  const handleAdd = (user: User): void => {
    const next: ClassInstructorPriority[] = [
      ...priorities,
      {
        zctip_user_id: user.usr_id,
        zctip_priority: priorities.length + 1,
        user_name: user.full_name,
      },
    ];
    onChange(normalize(next));
    setMenuAnchor(null);
  };

  const handleRemove = (index: number): void => {
    const next: ClassInstructorPriority[] = priorities.filter((_, i) => i !== index);
    onChange(normalize(next));
  };

  const handleMove = (index: number, direction: -1 | 1): void => {
    const target: number = index + direction;
    if (target < 0 || target >= priorities.length) return;
    const next: ClassInstructorPriority[] = [...priorities];
    const tmp: ClassInstructorPriority = next[index];
    next[index] = next[target];
    next[target] = tmp;
    onChange(normalize(next));
  };

  const resolveName = (entry: ClassInstructorPriority): string => {
    if (entry.user_name) return entry.user_name;
    const user: User | undefined = users.find((u) => u.usr_id === entry.zctip_user_id);
    return user ? user.full_name : `#${entry.zctip_user_id}`;
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      {priorities.length === 0 && (
        <Typography variant="body2" color="text.secondary">
          <Trans>Noch keine Trainer hinzugefügt</Trans>
        </Typography>
      )}
      {priorities.map((entry, index) => (
        <Box
          key={`${entry.zctip_user_id}-${index}`}
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            p: 1,
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 1,
          }}
        >
          <Typography
            variant="body2"
            sx={{ width: 32, fontWeight: 600, color: 'primary.main' }}
          >
            {index + 1}.
          </Typography>
          <Typography variant="body2" sx={{ flex: 1 }}>
            {resolveName(entry)}
          </Typography>
          <IconButton
            size="small"
            onClick={() => handleMove(index, -1)}
            disabled={index === 0}
          >
            <ArrowUpwardIcon fontSize="small" />
          </IconButton>
          <IconButton
            size="small"
            onClick={() => handleMove(index, 1)}
            disabled={index === priorities.length - 1}
          >
            <ArrowDownwardIcon fontSize="small" />
          </IconButton>
          <IconButton size="small" color="error" onClick={() => handleRemove(index)}>
            <DeleteOutlineIcon fontSize="small" />
          </IconButton>
        </Box>
      ))}
      {error && (
        <Typography variant="caption" color="error">
          {error}
        </Typography>
      )}
      <Box>
        <Button
          size="small"
          startIcon={<AddIcon />}
          onClick={(e) => setMenuAnchor(e.currentTarget)}
          disabled={available.length === 0}
        >
          <Trans>Trainer hinzufügen</Trans>
        </Button>
        {available.length === 0 && users.length === 0 && (
          <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
            <Trans>Keine Mitarbeiter geladen</Trans>
          </Typography>
        )}
        <Menu
          anchorEl={menuAnchor}
          open={Boolean(menuAnchor)}
          onClose={() => setMenuAnchor(null)}
          PaperProps={{ style: { maxHeight: 320 } }}
        >
          {available.map((user) => (
            <MenuItem key={user.usr_id} onClick={() => handleAdd(user)}>
              {user.full_name}
            </MenuItem>
          ))}
          {available.length === 0 && (
            <MenuItem disabled>{i18n._(t`Keine weiteren Mitarbeiter`)}</MenuItem>
          )}
        </Menu>
      </Box>
    </Box>
  );
};

export default InstructorPriorityPicker;
