// ItemTags.tsx
import React, { useState, MouseEvent, KeyboardEvent } from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import AddIcon from '@mui/icons-material/Add';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';

declare global {
  interface Window {
    confirmPopup: (opts: {
      title?: string;
      message?: React.ReactNode;
      confirmLabel?: string;
      cancelLabel?: string;
      danger?: boolean;
      showLoadingAfterConfirm?: boolean;
    }) => Promise<boolean>;
  }
}

interface ItemTagsProps {
  tags?: string[];
  onAdd: (tag: string) => void;
  onRemove: (tag: string) => void; // entfernt den Tag *von diesem Item*
}

const RADIUS = 10; // gleicher Radius für Tags & Add-Button

const styles = {
  wrap: {
    display: 'flex',
    alignItems: 'center',
    flexWrap: 'wrap',
    gap: 8,
  },
  // Add-Icon als dezenter, umrissener Pill-Button
  addIconBtn: {
    width: 28,
    height: 28,
    borderRadius: RADIUS,
    border: '1px solid rgba(0,0,0,0.12)',
    backgroundColor: 'transparent',
    boxShadow: 'none',
    padding: 0,
    '&:hover': {
      backgroundColor: 'var(--Google-Backround, rgba(236,244,254,1))',
    },
  },

  // Tag "Chip" als eigenständiger, minimalistischer Pill
  tag: {
    position: 'relative',
    display: 'inline-flex',
    alignItems: 'center',
    height: 28,
    borderRadius: RADIUS,
    border: '1px solid rgba(0,0,0,0.12)',
    backgroundColor: '#fff',
    padding: '0 10px',
    transition:
      'background-color 140ms ease, color 140ms ease, border-color 140ms ease',
    cursor: 'default',
    overflow: 'visible', // wichtig, damit das X außerhalb sichtbar ist
    '&:hover': {
      backgroundColor: 'var(--Google-Backround, rgba(236,244,254,1))',
      borderColor: 'rgba(0,0,0,0.20)',
    },
  },
  tagText: {
    fontFamily: 'Roboto, sans-serif',
    fontSize: 13,
    fontWeight: 400,
    lineHeight: 1,
    color: 'var(--Google-Navigation-Color, rgba(115,121,126,1))',
    whiteSpace: 'nowrap',
  },

  // Delete-Icon: außerhalb oben rechts; erscheint nur bei Hover
  deleteBtn: {
    position: 'absolute',
    right: -6, // außerhalb der Box
    top: -6, // außerhalb der Box
    transform: 'none',
    width: 20,
    height: 20,
    borderRadius: 10,
    opacity: 0,
    visibility: 'hidden',
    transition:
      'opacity 120ms ease, background-color 120ms ease, visibility 120ms ease',
    padding: 0,
    zIndex: 1,
    backgroundColor: '#fff',
    boxShadow: '0 2px 6px rgba(0,0,0,0.1)',
    border: '1px solid rgba(0,0,0,0.08)',
    '& svg': { fontSize: 14 },
    '&:hover': {
      backgroundColor: 'rgba(0,0,0,0.04)',
    },
  },
  tagHoverShowDelete: {
    '&:hover > .MuiIconButton-root': { opacity: 1, visibility: 'visible' },
  },

  input: {
    width: 160,
    '& .MuiOutlinedInput-root': {
      height: 28,
      borderRadius: RADIUS,
      padding: '0 8px',
      '& fieldset': { borderColor: 'rgba(0,0,0,0.2)' },
      '&:hover fieldset': { borderColor: 'rgba(0,0,0,0.5)' },
      '&.Mui-focused fieldset': { borderColor: 'rgba(0,0,0,0.8)' },
    },
    '& .MuiInputBase-input': {
      padding: 0,
      fontFamily: 'Roboto, sans-serif',
      fontSize: 13,
      fontWeight: 400,
    },
  },
};

const ItemTags: React.FC<ItemTagsProps> = ({ tags = [], onAdd, onRemove }) => {
  const [showInput, setShowInput] = useState(false);
  const [newTag, setNewTag] = useState('');

  // Ensure tags is always an array
  const tagsArr = Array.isArray(tags) ? tags : [];


  const openConfirmRemove = async (tag: string, e: MouseEvent<HTMLElement>) => {
    e.stopPropagation();
    // Hinweis: hier geht es um das Entfernen *von diesem Item*.
    // (Für globales Löschen aus allen Markierungen nutzt du dein anderes Confirm an der passenden Stelle.)
    const ok = await window.confirmPopup({
      title: 'Tag entfernen',
      message: (
        <span>
          Der Tag <b>{tag}</b> wird von diesem Eintrag entfernt. Fortfahren?
        </span>
      ),
      confirmLabel: 'Entfernen',
      cancelLabel: 'Abbrechen',
      danger: true,
    });
    if (!ok) return;
    onRemove(tag);
  };

  const handleAddClick = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    setShowInput(true);
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && newTag.trim()) {
      onAdd(newTag.trim());
      setNewTag('');
      setShowInput(false);
    }
    if (e.key === 'Escape') {
      setNewTag('');
      setShowInput(false);
    }
  };

  return (
    <Box sx={styles.wrap}>
      {/* Add-Button mit Hover-Text */}
      <Tooltip title='Tag hinzufügen' arrow>
        <IconButton
          sx={styles.addIconBtn}
          size='small'
          onClick={handleAddClick}
          aria-label='Add tag'
        >
          <AddIcon fontSize='small' />
        </IconButton>
      </Tooltip>

      {/* Tags */}
      {tagsArr.map((tag) => (
        <Box
          key={tag}
          sx={{ ...styles.tag, ...styles.tagHoverShowDelete }}
          onMouseDown={(e) => e.stopPropagation()}
        >
          <span
            style={{
              color: 'var(--Google-Navigation-Color, rgba(115,121,126,1))',
              fontFamily: 'Roboto, sans-serif',
              fontSize: 13,
              fontWeight: 400,
              lineHeight: 1,
              whiteSpace: 'nowrap',
            }}
          >
            {tag}
          </span>

          {/* Delete-Icon (außerhalb oben rechts) */}
          <IconButton
            sx={styles.deleteBtn}
            size='small'
            aria-label={`Remove ${tag}`}
            onClick={(e) => openConfirmRemove(tag, e)}
            tabIndex={-1}
          >
            <CloseRoundedIcon />
          </IconButton>
        </Box>
      ))}

      {/* Inline-Input zum Hinzufügen */}
      {showInput && (
        <TextField
          sx={styles.input}
          size='small'
          placeholder='Neuer Tag'
          variant='outlined'
          value={newTag}
          onChange={(e) => setNewTag(e.target.value)}
          onKeyDown={handleKeyDown}
          autoFocus
        />
      )}
    </Box>
  );
};

export default ItemTags;
