import { useMemo } from 'react';
import { DateRange } from 'react-date-range';
import { de } from 'date-fns/locale';
import { buildSelectionRange } from '../utils/dateUtils';

const WEEKDAY_INDEX = {
  Sonntag: 0,
  Montag: 1,
  Dienstag: 2,
  Mittwoch: 3,
  Donnerstag: 4,
  Freitag: 5,
  Samstag: 6
};

const formatDateKey = (value) => {
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) {
    return '';
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatTime = (value) => {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return '';
  }
  return date.toLocaleTimeString('de-DE', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

const formatRangeText = (entry) => {
  const range = entry?.desiredDateRange || (entry?.desiredDate ? { start: entry.desiredDate, end: entry.desiredDate } : null);
  if (range?.start || range?.end) {
    const start = range.start || range.end;
    const end = range.end || range.start;
    return start === end ? start : `${start} bis ${end}`;
  }
  return entry?.desiredWeekday || 'aktiv ohne Zeitfenster';
};

const entryHasPlannedDay = (entry, date, dayKey) => {
  if (!entry?.active || entry.hidden) {
    return false;
  }
  const range = entry.desiredDateRange || (entry.desiredDate ? { start: entry.desiredDate, end: entry.desiredDate } : null);
  if (range?.start || range?.end) {
    const start = range.start || range.end;
    const end = range.end || range.start;
    return dayKey >= start && dayKey <= end;
  }
  return entry.desiredWeekday ? WEEKDAY_INDEX[entry.desiredWeekday] === date.getDay() : false;
};

const RangePickerModal = ({
  entry,
  minDate,
  config,
  registeredPickups,
  onSelectRange,
  onResetRange,
  onClose
}) => {
  const registeredPickupsByDate = useMemo(() => {
    const byDate = new Map();
    (Array.isArray(registeredPickups) ? registeredPickups : []).forEach((pickup) => {
      const key = formatDateKey(pickup?.date);
      if (key) {
        const items = byDate.get(key) || [];
        items.push(pickup);
        byDate.set(key, items);
      }
    });
    return byDate;
  }, [registeredPickups]);

  const plannedEntries = useMemo(
    () => (Array.isArray(config) ? config : []).filter((item) => item?.active && !item.hidden),
    [config]
  );

  if (!entry) {
    return null;
  }

  const renderDayContent = (date) => {
    const dayKey = formatDateKey(date);
    const foodsharingPickups = registeredPickupsByDate.get(dayKey) || [];
    const managerPlans = plannedEntries.filter((item) => entryHasPlannedDay(item, date, dayKey));
    const hasFoodsharingPickup = foodsharingPickups.length > 0;
    const hasManagerPlan = managerPlans.length > 0;
    const titleParts = [
      ...foodsharingPickups.map((pickup) => {
        const time = formatTime(pickup.date);
        const label = pickup.storeName || `Store ${pickup.storeId || ''}`.trim();
        const description = pickup.description ? `, ${pickup.description}` : '';
        return `Foodsharing: ${label}${time ? ` ${time}` : ''}${description}`;
      }),
      ...managerPlans.map((plan) => `Foodsharing Manager: ${plan.label || `Store ${plan.id}`} (${formatRangeText(plan)})`)
    ];
    return (
      <span
        className="relative inline-flex h-7 w-7 items-center justify-center"
        title={titleParts.length > 0 ? titleParts.join('\n') : undefined}
      >
        <span>{date.getDate()}</span>
        {(hasFoodsharingPickup || hasManagerPlan) && (
          <span className="absolute bottom-0 flex gap-0.5">
            {hasFoodsharingPickup && <span className="h-1.5 w-1.5 rounded-full bg-green-600" />}
            {hasManagerPlan && <span className="h-1.5 w-1.5 rounded-full bg-emerald-600" />}
          </span>
        )}
      </span>
    );
  };

  return (
    <div className="range-picker-backdrop" onClick={onClose}>
      <div
        className="range-picker-modal bg-white rounded-2xl shadow-2xl w-full max-w-lg"
        onClick={(event) => event.stopPropagation()}
      >
        <div className="px-5 pt-5 pb-3 border-b">
          <p className="text-xs uppercase tracking-wide text-gray-500">Zeitraum auswählen für</p>
          <p className="text-lg font-semibold text-gray-900">{entry.label || `Store ${entry.id}`}</p>
        </div>
        <div className="px-2 py-4">
          <DateRange
            onChange={(ranges) => {
              const { startDate, endDate } = ranges.selection;
              onSelectRange(startDate, endDate);
            }}
            moveRangeOnFirstSelection={false}
            ranges={[
              buildSelectionRange(
                entry.desiredDateRange?.start,
                entry.desiredDateRange?.end,
                minDate
              )
            ]}
            rangeColors={['#2563EB']}
            months={1}
            direction="horizontal"
            showDateDisplay={false}
            locale={de}
            minDate={minDate}
            dayContentRenderer={renderDayContent}
          />
          <div className="mt-3 flex flex-wrap items-center gap-3 px-3 text-xs text-gray-600">
            <span className="inline-flex items-center gap-1">
              <span className="h-2 w-2 rounded-full bg-green-600" />
              Foodsharing eingetragen
            </span>
            <span className="inline-flex items-center gap-1">
              <span className="h-2 w-2 rounded-full bg-emerald-600" />
              Foodsharing Manager geplant
            </span>
          </div>
        </div>
        <div className="flex items-center justify-between px-5 py-3 border-t bg-gray-50 rounded-b-2xl">
          <button type="button" className="text-sm text-gray-600 hover:text-gray-900" onClick={onResetRange}>
            Zurücksetzen
          </button>
          <div className="flex items-center gap-3">
            <button type="button" className="text-sm text-gray-600 hover:text-gray-900" onClick={onClose}>
              Abbrechen
            </button>
            <button
              type="button"
              className="text-sm font-semibold text-white bg-green-600 hover:bg-green-700 px-4 py-2 rounded-md"
              onClick={onClose}
            >
              Fertig
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RangePickerModal;
