import React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { ShiftTemplate } from '../../types/shift';
import { getContrastColor } from '../../utils/colorUtils';
import { LoadingState, EmptyState } from '../shared';

interface ShiftTemplatesPanelProps {
  templates: ShiftTemplate[];
  loading: boolean;
  onTemplateDragStart: (e: React.DragEvent, template: ShiftTemplate) => void;
  onTemplateDragEnd?: () => void;
  hasAdminAccess?: boolean;
  onCreateTemplate?: () => void;
  onEditTemplate?: (template: ShiftTemplate) => void;
}

const ShiftTemplatesPanel: React.FC<ShiftTemplatesPanelProps> = ({
  templates,
  loading,
  onTemplateDragStart,
  onTemplateDragEnd,
  hasAdminAccess = false,
  onCreateTemplate,
  onEditTemplate,
}) => {
  const { i18n } = useLingui();

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', flex: 1 }}>
      {/* Scrollable template list */}
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        {loading ? (
          <LoadingState size={24} />
        ) : templates.length === 0 ? (
          <EmptyState
            title={i18n._(t`Keine Vorlagen`)}
            message={i18n._(t`Keine Vorlagen verfügbar`)}
          />
        ) : (
          <Box display="flex" flexDirection="column" gap={1}>
            {templates.map((template) => (
              <Box
                key={template.zst_id}
                draggable
                onDragStart={(e) => onTemplateDragStart(e, template)}
                onDragEnd={onTemplateDragEnd}
                sx={{
                  p: 1.5,
                  borderRadius: 1,
                  backgroundColor: template.zst_color,
                  color: getContrastColor(template.zst_color),
                  cursor: 'grab',
                  position: 'relative',
                  '&:active': {
                    cursor: 'grabbing',
                  },
                  '&:hover': {
                    opacity: 0.9,
                    boxShadow: 2,
                  },
                  pb: hasAdminAccess && onEditTemplate ? 4 : 1.5,
                }}
              >
                <Typography variant="body2" fontWeight="bold">
                  {template.zst_name}
                </Typography>
                <Typography variant="caption" display="block">
                  {template.zst_start_time.substring(0, 5)} - {template.zst_end_time.substring(0, 5)}
                </Typography>
                {template.zst_min_workers > 0 && (
                  <Chip
                    label={`Min: ${template.zst_min_workers}`}
                    size="small"
                    sx={{
                      mt: 0.5,
                      height: 18,
                      fontSize: '0.65rem',
                      backgroundColor: 'rgba(255, 255, 255, 0.2)',
                      color: 'inherit',
                    }}
                  />
                )}

                {hasAdminAccess && onEditTemplate && (
                  <Tooltip title={i18n._(t`Vorlage bearbeiten`)}>
                    <IconButton
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        onEditTemplate(template);
                      }}
                      onMouseDown={(e) => e.stopPropagation()}
                      sx={{
                        position: 'absolute',
                        bottom: 4,
                        right: 4,
                        width: 24,
                        height: 24,
                        backgroundColor: 'rgba(255, 255, 255, 0.85)',
                        color: template.zst_color,
                        '&:hover': {
                          backgroundColor: 'rgba(255, 255, 255, 1)',
                          transform: 'scale(1.1)',
                        },
                        transition: 'all 0.2s ease-in-out',
                      }}
                    >
                      <EditIcon sx={{ fontSize: 14 }} />
                    </IconButton>
                  </Tooltip>
                )}
              </Box>
            ))}
          </Box>
        )}
      </Box>

      {/* Fixed bottom button */}
      {hasAdminAccess && onCreateTemplate && (
        <Box sx={{ p: 2, pt: 1, flexShrink: 0, borderTop: '1px solid #dee2e6' }}>
          <Button
            variant="outlined"
            color="primary"
            size="small"
            fullWidth
            startIcon={<AddIcon />}
            onClick={onCreateTemplate}
            className="add-template-button"
            sx={{ textTransform: 'none', borderStyle: 'dashed' }}
          >
            <Trans>Vorlage</Trans>
          </Button>
        </Box>
      )}
    </Box>
  );
};

// Memoize to prevent re-renders when parent state changes but templates are the same
export default React.memo(ShiftTemplatesPanel, (prevProps, nextProps) => {
  return (
    prevProps.templates.length === nextProps.templates.length &&
    prevProps.templates.every((t, i) => {
      const n = nextProps.templates[i];
      return n && t.zst_id === n.zst_id &&
        t.zst_name === n.zst_name &&
        t.zst_start_time === n.zst_start_time &&
        t.zst_end_time === n.zst_end_time &&
        t.zst_color === n.zst_color &&
        t.zst_min_workers === n.zst_min_workers;
    }) &&
    prevProps.loading === nextProps.loading &&
    prevProps.hasAdminAccess === nextProps.hasAdminAccess
  );
});
