import { AlertCircle, ChevronLeft, ChevronRight, Clock, Users } from 'lucide-react';
import { formatDateWithWeekday } from '../../../utils/Formatters';
import { DURATION_OPTIONS, TIME_PERIODS, TIME_SLOTS } from '../../constans';
import TimeSlotButton from '../components/TimeSlotButton';
import type { Step2Props } from '../../types';

const Step2TimeSelection: React.FC<Step2Props> = ({ dateInfo, warning, actions, utils }) => {
  const { selectedDate, selectedTime, duration } = dateInfo;
  const dayStatus = utils.getDayDetailedStatus(selectedDate);

  const getTimeSlotStatus = (time: string) => {
    const isBusy = utils.isTimeSlotBusy(selectedDate, time, duration);
    const bookingsCount = utils.getBookingsCount(selectedDate, time);

    if (isBusy) return 'busy';
    if (bookingsCount > 0) return 'partial';
    return 'free';
  };

  const getNextFreeTime = () => {
    const now = new Date();
    const isToday = selectedDate === now.toISOString().slice(0, 10);
    const currentTimeInMinutes = now.getHours() * 60 + now.getMinutes();

    for (const slot of TIME_SLOTS) {
      const [hours, minutes] = slot.time.split(':').map(Number);
      const slotTimeInMinutes = hours * 60 + minutes;

      if (isToday && slotTimeInMinutes <= currentTimeInMinutes) continue;
      if (getTimeSlotStatus(slot.time) === 'free') return slot.time;
    }
    return null;
  };

  const nextFreeTime = getNextFreeTime();

  return (
    <>
      <div className="text-xl font-bold text-white mb-2">Шаг 2: Выберите время</div>
      <div className="text-sm text-neutral-400 mb-4">{formatDateWithWeekday(selectedDate)}</div>

      {/* Информация о дне */}
      <DayStatusCard dayStatus={dayStatus} />

      {/* Выбор продолжительности */}
      <DurationSelector
        duration={duration}
        options={DURATION_OPTIONS}
        onChange={actions.onDurationChange}
      />

      {/* Рекомендация свободного времени */}
      {nextFreeTime && (
        <NextFreeTimeHint time={nextFreeTime} onSelect={() => actions.onTimeSelect(nextFreeTime)} />
      )}

      {/* Временная сетка */}
      <div className="mb-4">
        <div className="text-sm text-neutral-400 mb-3">Выберите удобное время:</div>

        {Object.entries(TIME_PERIODS).map(([period, info]) => (
          <TimePeriodSection
            key={period}
            title={info.label}
            subtitle={info.range}
            slots={TIME_SLOTS.filter(slot => slot.period === period)}
            selectedTime={selectedTime}
            onTimeSelect={actions.onTimeSelect}
            getTimeSlotStatus={getTimeSlotStatus}
            getBookingsCount={time => utils.getBookingsCount(selectedDate, time)}
          />
        ))}
      </div>

      {/* Выбранное время */}
      {selectedTime && <SelectedTimeInfo selectedTime={selectedTime} duration={duration} />}

      {/* Предупреждение */}
      {warning.show && (
        <WarningMessage onConfirm={warning.onConfirm} onDismiss={warning.onDismiss} />
      )}

      {/* Навигация */}
      <NavigationButtons
        onPrev={actions.onPrevStep}
        onNext={actions.onNextStep}
        canProceed={!!selectedTime && !warning.show}
      />
    </>
  );
};

// Вспомогательные компоненты
const DayStatusCard: React.FC<{ dayStatus: any }> = ({ dayStatus }) => (
  <div className="bg-neutral-800 rounded-xl p-4 mb-4">
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-3">
        <div className={`w-3 h-3 rounded-full ${dayStatus.color}`} />
        <span className="text-white font-medium">{dayStatus.label}</span>
      </div>
      <div className="flex items-center gap-4 text-xs">
        <span className="text-green-400">
          <Clock size={14} className="inline mr-1" />
          {dayStatus.freeHours}ч свободно
        </span>
        <span className="text-yellow-400">
          <Users size={14} className="inline mr-1" />
          {dayStatus.details.length} записей
        </span>
      </div>
    </div>
  </div>
);

const DurationSelector: React.FC<{
  duration: number;
  options: number[];
  onChange: (duration: number) => void;
}> = ({ duration, options, onChange }) => (
  <div className="mb-6">
    <label className="text-sm text-neutral-400 mb-2 block">Продолжительность услуги:</label>
    <div className="grid grid-cols-5 gap-2">
      {options.map(minutes => (
        <button
          key={minutes}
          onClick={() => onChange(minutes)}
          className={`py-2 px-3 rounded-lg text-sm font-medium transition-all ${
            duration === minutes
              ? 'bg-fuchsia-500 text-white'
              : 'bg-neutral-700 text-neutral-300 hover:bg-neutral-600'
          }`}
        >
          {minutes >= 60 ? `${minutes / 60}ч` : `${minutes}м`}
        </button>
      ))}
    </div>
    <div className="text-xs text-neutral-500 mt-2">
      Выбрано:{' '}
      {duration >= 60 ? `${duration / 60} час${duration === 60 ? '' : 'а'}` : `${duration} минут`}
    </div>
  </div>
);

const TimePeriodSection: React.FC<{
  title: string;
  subtitle: string;
  slots: any[];
  selectedTime: string;
  onTimeSelect: (time: string) => void;
  getTimeSlotStatus: (time: string) => string;
  getBookingsCount: (time: string) => number;
}> = ({
  title,
  subtitle,
  slots,
  selectedTime,
  onTimeSelect,
  getTimeSlotStatus,
  getBookingsCount,
}) => (
  <div className="mb-4">
    <div className="text-xs text-neutral-500 mb-2">
      {title} ({subtitle})
    </div>
    <div className="grid grid-cols-3 gap-2">
      {slots.map(({ time }) => (
        <TimeSlotButton
          key={time}
          time={time}
          status={getTimeSlotStatus(time) as any}
          bookingsCount={getBookingsCount(time)}
          isSelected={time === selectedTime}
          onClick={() => onTimeSelect(time)}
        />
      ))}
    </div>
  </div>
);

const NavigationButtons: React.FC<{
  onPrev: () => void;
  onNext: () => void;
  canProceed: boolean;
}> = ({ onPrev, onNext, canProceed }) => (
  <div className="flex gap-3">
    <button
      onClick={onPrev}
      className="flex-1 py-3 rounded-xl bg-neutral-800 text-white font-semibold hover:bg-neutral-700 transition flex items-center justify-center gap-2"
    >
      <ChevronLeft size={20} />
      Назад
    </button>
    <button
      onClick={onNext}
      disabled={!canProceed}
      className={`flex-1 py-3 rounded-xl font-bold transition flex items-center justify-center gap-2 ${
        canProceed
          ? 'bg-gradient-to-r from-fuchsia-500 to-fuchsia-600 text-white hover:from-fuchsia-600 hover:to-fuchsia-700'
          : 'bg-neutral-700 text-neutral-400 cursor-not-allowed'
      }`}
    >
      Далее
      <ChevronRight size={20} />
    </button>
  </div>
);
// Добавь эти компоненты в тот же файл Step2TimeSelection.tsx после NavigationButtons

const NextFreeTimeHint: React.FC<{
  time: string;
  onSelect: () => void;
}> = ({ time, onSelect }) => (
  <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-3 mb-4">
    <div className="flex items-center justify-between">
      <div className="text-sm text-green-400">💡 Ближайшее свободное время: {time}</div>
      <button
        onClick={onSelect}
        className="px-3 py-1 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500/30 transition text-sm"
      >
        Выбрать
      </button>
    </div>
  </div>
);

const SelectedTimeInfo: React.FC<{
  selectedTime: string;
  duration: number;
}> = ({ selectedTime, duration }) => {
  const calculateEndTime = () => {
    const [hours, minutes] = selectedTime.split(':').map(Number);
    const endTime = new Date(2000, 0, 1, hours, minutes + duration);
    return `${endTime.getHours().toString().padStart(2, '0')}:${endTime
      .getMinutes()
      .toString()
      .padStart(2, '0')}`;
  };

  return (
    <div className="bg-fuchsia-500/10 border border-fuchsia-500/30 rounded-lg p-3 mb-4">
      <div className="text-sm text-fuchsia-400">
        ✓ Выбрано: {selectedTime} - {calculateEndTime()}
        <span className="text-xs text-neutral-400 ml-2">
          ({duration >= 60 ? `${duration / 60} ч.` : `${duration} мин.`})
        </span>
      </div>
    </div>
  );
};

const WarningMessage: React.FC<{
  onConfirm: () => void;
  onDismiss: () => void;
}> = ({ onConfirm, onDismiss }) => (
  <div className="mb-6 bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4">
    <div className="flex items-start gap-3">
      <AlertCircle className="text-yellow-500 mt-1" size={20} />
      <div className="flex-1">
        <div className="text-yellow-400 font-semibold mb-1">Внимание!</div>
        <div className="text-sm text-neutral-300 mb-3">
          На это время уже есть запись. Вы можете добавить еще одного клиента, если работаете с
          несколькими одновременно.
        </div>
        <div className="flex gap-2">
          <button
            onClick={onConfirm}
            className="px-4 py-2 bg-yellow-500/20 text-yellow-400 rounded-lg hover:bg-yellow-500/30 transition text-sm font-medium"
          >
            <Users className="inline mr-1" size={16} />
            Добавить еще одного
          </button>
          <button
            onClick={onDismiss}
            className="px-4 py-2 bg-neutral-800 text-white rounded-lg hover:bg-neutral-700 transition text-sm"
          >
            Выбрать другое время
          </button>
        </div>
      </div>
    </div>
  </div>
);

export default Step2TimeSelection;

// TimeSlotButton.tsx
import React from 'react';
import { Check } from 'lucide-react';

interface TimeSlotButtonProps {
  time: string;
  status: 'free' | 'busy';
  isSelected: boolean;
  onClick: () => void;
  clientName?: string;
}

const TimeSlotButton: React.FC<TimeSlotButtonProps> = ({
  time,
  status,
  isSelected,
  onClick,
  clientName,
}) => {
  return (
    <button
      onClick={onClick}
      disabled={status === 'busy'}
      className={`
        relative py-3 px-2 rounded-xl text-sm font-medium transition-all transform
        ${status === 'busy' 
          ? 'bg-red-500/10 text-red-400 border border-red-500/20 cursor-not-allowed' 
          : isSelected
          ? 'bg-fuchsia-500 text-white scale-105 shadow-lg shadow-fuchsia-500/30'
          : 'bg-neutral-700 text-white hover:bg-neutral-600 hover:scale-105 active:scale-100'
        }
      `}
    >
      <div className="text-base font-semibold">{time}</div>
      {status === 'busy' && clientName && (
        <div className="text-xs mt-0.5 truncate opacity-70">{clientName}</div>
      )}
      {isSelected && (
        <div className="absolute -top-1 -right-1 bg-white text-fuchsia-500 rounded-full p-0.5">
          <Check size={12} strokeWidth={3} />
        </div>
      )}
    </button>
  );
};

export default TimeSlotButton;

step2 нужно сделать лучше юх ай более функциональный так сказать, при выборе времени