import React, { useState } 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 Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import CircularProgress from '@mui/material/CircularProgress';
import Tooltip from '@mui/material/Tooltip';
import PersonSearchIcon from '@mui/icons-material/PersonSearch';
import VolunteerActivismIcon from '@mui/icons-material/VolunteerActivism';
import CancelIcon from '@mui/icons-material/Cancel';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import WidgetWrapper from './WidgetWrapper';
import {
  OutgoingReplacementRequest,
  IncomingReplacementOpportunity,
  ShiftInfo,
} from '../../types/swapReplacement';

interface ReplacementsWidgetProps {
  outgoingReplacements: OutgoingReplacementRequest[];
  incomingReplacements: IncomingReplacementOpportunity[];
  loading: boolean;
  onRefresh: () => void;
  onCancelReplacement: (assignmentId: number) => Promise<void>;
  onVolunteerReplacement: (assignmentId: number) => Promise<void>;
  actionLoading: boolean;
}

function formatShiftDate(shift: ShiftInfo): string {
  const date = new Date(shift.zs_date + 'T00:00:00');
  const day = date.getDate().toString().padStart(2, '0');
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  return `${day}.${month}`;
}

function formatShiftTime(shift: ShiftInfo): string {
  const start = shift.zs_start_time?.substring(0, 5) || '';
  const end = shift.zs_end_time?.substring(0, 5) || '';
  return `${start} - ${end}`;
}

function getContrastColor(hexColor: string): string {
  if (!hexColor) return '#000000';
  const r: number = parseInt(hexColor.slice(1, 3), 16);
  const g: number = parseInt(hexColor.slice(3, 5), 16);
  const b: number = parseInt(hexColor.slice(5, 7), 16);
  const luminance: number = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return luminance > 0.5 ? '#000000' : '#FFFFFF';
}

const tabCounterSx = {
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  minWidth: 20,
  height: 20,
  borderRadius: '10px',
  px: 0.75,
  fontSize: '0.7rem',
  fontWeight: 600,
  lineHeight: 1,
} as const;

const ReplacementsWidget: React.FC<ReplacementsWidgetProps> = ({
  outgoingReplacements,
  incomingReplacements,
  loading,
  onRefresh,
  onCancelReplacement,
  onVolunteerReplacement,
  actionLoading,
}) => {
  const { i18n } = useLingui();
  const [tab, setTab] = useState<number>(0);

  const totalCount: number = outgoingReplacements.length + incomingReplacements.length;

  return (
    <WidgetWrapper
      title={i18n._(t`Vertretungen`)}
      icon={<PersonSearchIcon />}
      loading={loading}
      onRefresh={onRefresh}
      badge={totalCount}
      badgeColor={incomingReplacements.length > 0 ? 'warning' : 'primary'}
      empty={totalCount === 0}
      emptyMessage={i18n._(t`Keine Vertretungsanfragen`)}
      emptyIcon={<PersonSearchIcon sx={{ fontSize: 40 }} />}
    >
      <Box>
        <Tabs
          value={tab}
          onChange={(_, v: number) => setTab(v)}
          variant="fullWidth"
          sx={{
            minHeight: 40,
            borderBottom: '1px solid',
            borderColor: 'divider',
            '& .MuiTab-root': {
              minHeight: 40,
              py: 1,
              fontSize: '0.8rem',
              fontWeight: 500,
              textTransform: 'none',
              letterSpacing: '-0.01em',
            },
            '& .MuiTabs-indicator': {
              height: 2,
            },
          }}
        >
          <Tab
            label={
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                <Trans>Meine Anfragen</Trans>
                {outgoingReplacements.length > 0 && (
                  <Box
                    component="span"
                    sx={{
                      ...tabCounterSx,
                      bgcolor: 'primary.main',
                      color: 'primary.contrastText',
                    }}
                  >
                    {outgoingReplacements.length}
                  </Box>
                )}
              </Box>
            }
          />
          <Tab
            label={
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                <Trans>Verfügbare Schichten</Trans>
                {incomingReplacements.length > 0 && (
                  <Box
                    component="span"
                    sx={{
                      ...tabCounterSx,
                      bgcolor: 'warning.main',
                      color: 'warning.contrastText',
                    }}
                  >
                    {incomingReplacements.length}
                  </Box>
                )}
              </Box>
            }
          />
        </Tabs>

        <List disablePadding sx={{ overflow: 'auto' }}>
          {tab === 0 && outgoingReplacements.map((req: OutgoingReplacementRequest) => (
            <ListItem
              key={req.request_assignment_id}
              sx={{
                borderBottom: '1px solid',
                borderColor: 'divider',
                py: 2,
                px: 2.5,
                flexDirection: 'column',
                alignItems: 'stretch',
                gap: 1,
                '&:last-child': { borderBottom: 'none' },
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                <Box>
                  <Typography
                    variant="body2"
                    sx={{ fontWeight: 600, color: 'text.primary', fontSize: '0.8rem', letterSpacing: '-0.01em' }}
                  >
                    {formatShiftDate(req.my_shift)}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{ color: 'text.disabled', fontVariantNumeric: 'tabular-nums' }}
                  >
                    {formatShiftTime(req.my_shift)}
                  </Typography>
                </Box>
                <Typography
                  variant="body2"
                  sx={{ color: 'text.secondary', fontSize: '0.8rem' }}
                >
                  {req.my_shift.display_name}
                </Typography>
              </Box>

              {req.zsa_replacement_notes && (
                <Box
                  sx={{
                    bgcolor: 'grey.50',
                    borderRadius: 1.5,
                    px: 1.5,
                    py: 1,
                  }}
                >
                  <Typography
                    variant="caption"
                    sx={{ color: 'text.secondary', fontStyle: 'italic', lineHeight: 1.5 }}
                  >
                    {req.zsa_replacement_notes}
                  </Typography>
                </Box>
              )}

              <Box sx={{ pt: 0.5 }}>
                <Button
                  size="small"
                  variant="contained"
                  disableElevation
                  color="error"
                  startIcon={actionLoading ? <CircularProgress size={14} /> : <CancelIcon />}
                  disabled={actionLoading}
                  onClick={() => onCancelReplacement(req.request_assignment_id)}
                  sx={{
                    fontSize: '0.75rem',
                    fontWeight: 500,
                    textTransform: 'none',
                    borderRadius: 1.5,
                    px: 2,
                    py: 0.5,
                  }}
                >
                  <Trans>Abbrechen</Trans>
                </Button>
              </Box>
            </ListItem>
          ))}

          {tab === 0 && outgoingReplacements.length === 0 && (
            <Box sx={{ py: 5, px: 3, textAlign: 'center' }}>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                <Trans>Keine Vertretungsanfragen gestellt</Trans>
              </Typography>
            </Box>
          )}

          {tab === 1 && incomingReplacements.map((opp: IncomingReplacementOpportunity) => (
            <ListItem
              key={opp.request_assignment_id}
              sx={{
                borderBottom: '1px solid',
                borderColor: 'divider',
                py: 2,
                px: 2.5,
                flexDirection: 'column',
                alignItems: 'stretch',
                gap: 1,
                '&:last-child': { borderBottom: 'none' },
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                <Box>
                  <Typography
                    variant="body2"
                    sx={{ fontWeight: 600, color: 'text.primary', fontSize: '0.8rem', letterSpacing: '-0.01em' }}
                  >
                    {formatShiftDate(opp.their_shift)}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{ color: 'text.disabled', fontVariantNumeric: 'tabular-nums' }}
                  >
                    {formatShiftTime(opp.their_shift)}
                  </Typography>
                </Box>
                <Box sx={{ flex: 1 }}>
                  <Typography
                    variant="body2"
                    sx={{ color: 'text.secondary', fontSize: '0.8rem' }}
                  >
                    {opp.their_shift.display_name}
                  </Typography>
                </Box>
                {opp.their_shift.department && (
                  <Typography
                    variant="caption"
                    sx={{ color: 'text.disabled' }}
                  >
                    {opp.their_shift.department.ber_name}
                  </Typography>
                )}
              </Box>

              {opp.original_user && (
                <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                  <Trans>Von:</Trans> {opp.original_user.name}
                </Typography>
              )}

              {opp.required_role && (
                <Box sx={{ pt: 0.25 }}>
                  <Chip
                    label={opp.required_role.zr_name}
                    size="small"
                    sx={{
                      height: 22,
                      fontSize: '0.7rem',
                      fontWeight: 500,
                      borderRadius: 1,
                      bgcolor: opp.required_role.zr_color || 'grey.200',
                      color: opp.required_role.zr_color ? getContrastColor(opp.required_role.zr_color) : 'text.primary',
                    }}
                  />
                </Box>
              )}

              {opp.zsa_replacement_notes && (
                <Box
                  sx={{
                    bgcolor: 'grey.50',
                    borderRadius: 1.5,
                    px: 1.5,
                    py: 1,
                  }}
                >
                  <Typography
                    variant="caption"
                    sx={{ color: 'text.secondary', fontStyle: 'italic', lineHeight: 1.5 }}
                  >
                    {opp.zsa_replacement_notes}
                  </Typography>
                </Box>
              )}

              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, pt: 0.5 }}>
                <Button
                  size="small"
                  variant="contained"
                  disableElevation
                  color="success"
                  startIcon={actionLoading ? <CircularProgress size={14} /> : <VolunteerActivismIcon />}
                  disabled={actionLoading || !opp.user_is_compatible}
                  onClick={() => onVolunteerReplacement(opp.request_assignment_id)}
                  sx={{
                    fontSize: '0.75rem',
                    fontWeight: 500,
                    textTransform: 'none',
                    borderRadius: 1.5,
                    px: 2,
                    py: 0.5,
                  }}
                >
                  <Trans>Übernehmen</Trans>
                </Button>
                {!opp.user_is_compatible && opp.incompatibility_reason && (
                  <Tooltip title={opp.incompatibility_reason}>
                    <InfoOutlinedIcon fontSize="small" color="disabled" />
                  </Tooltip>
                )}
              </Box>
            </ListItem>
          ))}

          {tab === 1 && incomingReplacements.length === 0 && (
            <Box sx={{ py: 5, px: 3, textAlign: 'center' }}>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                <Trans>Keine verfügbaren Schichten</Trans>
              </Typography>
            </Box>
          )}
        </List>
      </Box>
    </WidgetWrapper>
  );
};

export default React.memo(ReplacementsWidget);
