import React from 'react';
import {
  Box,
  Chip,
  Link,
  Skeleton,
  Typography,
} from '@mui/material';
import { DirectionsCar as DirectionsCarIcon } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { bookingApi } from '../../services/bookings';
import type { FahrzeugBuchungListItem } from '../../types/booking.types';
import { BUCHUNGS_ART_COLORS, BUCHUNGS_ART_LABELS } from '../../types/booking.types';
import { ListCard } from '../templates/ListCard';
import { WidgetCard } from '../templates/WidgetCard';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const WEEKDAY_SHORT = ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'];

function formatDateShort(isoString: string): string {
  const d = new Date(isoString);
  const weekday = WEEKDAY_SHORT[d.getDay()];
  const day = String(d.getDate()).padStart(2, '0');
  const month = String(d.getMonth() + 1).padStart(2, '0');
  return `${weekday} ${day}.${month}.`;
}

function formatTime(isoString: string): string {
  const d = new Date(isoString);
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')} Uhr`;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

const FETCH_LIMIT = 10;
const DISPLAY_LIMIT = 5;

const VehicleBookingListWidget: React.FC = () => {
  const { data: rawItems = [], isLoading, isError } = useQuery<FahrzeugBuchungListItem[]>({
    queryKey: ['upcoming-vehicle-bookings'],
    queryFn: () => bookingApi.getUpcoming(FETCH_LIMIT),
  });

  const items = React.useMemo(
    () => rawItems.filter((b) => !b.abgesagt).slice(0, DISPLAY_LIMIT),
    [rawItems],
  );

  if (isError) {
    return (
      <WidgetCard
        title="Nächste Fahrzeugbuchungen"
        icon={<DirectionsCarIcon fontSize="small" />}
        isError
        errorMessage="Buchungen konnten nicht geladen werden."
      />
    );
  }

  return (
    <ListCard
      title="Nächste Fahrzeugbuchungen"
      icon={<DirectionsCarIcon fontSize="small" />}
      items={items}
      renderItem={(booking) => {
        const color = BUCHUNGS_ART_COLORS[booking.buchungs_art] ?? '#9e9e9e';
        const label = BUCHUNGS_ART_LABELS[booking.buchungs_art] ?? booking.buchungs_art;
        return (
          <Box
            sx={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: 1.5,
            }}
          >
            {/* Colored type indicator dot */}
            <Box
              sx={{
                mt: '4px',
                flexShrink: 0,
                width: 10,
                height: 10,
                borderRadius: '50%',
                bgcolor: color,
              }}
            />

            {/* Date + title block */}
            <Box sx={{ flex: 1, minWidth: 0 }}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 0.75,
                  flexWrap: 'wrap',
                  mb: 0.25,
                }}
              >
                <Typography
                  variant="caption"
                  sx={{
                    color: 'text.secondary',
                    fontVariantNumeric: 'tabular-nums',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {formatDateShort(booking.beginn)}
                  {' '}&middot;{' '}
                  {formatTime(booking.beginn)}
                </Typography>

                <Chip
                  label={label}
                  size="small"
                  sx={{
                    height: 16,
                    fontSize: '0.65rem',
                    bgcolor: `${color}22`,
                    color: color,
                    border: `1px solid ${color}55`,
                    fontWeight: 600,
                    '& .MuiChip-label': { px: '5px' },
                  }}
                />
              </Box>

              <Typography
                variant="body2"
                sx={{
                  fontWeight: 500,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
              >
                {booking.titel}
              </Typography>

              <Typography
                variant="caption"
                color="text.secondary"
                sx={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  display: 'block',
                }}
              >
                {booking.fahrzeug_name}
              </Typography>
            </Box>
          </Box>
        );
      }}
      isLoading={isLoading}
      skeletonCount={5}
      skeletonItem={
        <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'flex-start' }}>
          <Skeleton variant="circular" width={10} height={10} sx={{ mt: '4px' }} animation="wave" />
          <Box sx={{ flex: 1 }}>
            <Skeleton variant="text" width="70%" animation="wave" />
            <Skeleton variant="text" width="40%" animation="wave" />
          </Box>
        </Box>
      }
      emptyMessage="Keine bevorstehenden Buchungen"
      footer={
        <Box sx={{ textAlign: 'right' }}>
          <Link
            component={RouterLink}
            to="/kalender?tab=1"
            underline="hover"
            variant="body2"
            sx={{ fontWeight: 500 }}
          >
            Alle Buchungen
          </Link>
        </Box>
      }
    />
  );
};

export default VehicleBookingListWidget;
