'use client';

import { Clock } from 'lucide-react';
import { formatTime } from '@/lib/utils';
import type { Location } from '@/types/api';

const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

type HoursGroup = { days: string; hours: string; closed: boolean };

export function getGroupedHours(loc: Location): HoursGroup[] {
  if (!loc.schedules || loc.schedules.length === 0) {
    if (loc.opening_time && loc.closing_time) {
      return [{ days: 'Daily', hours: `${formatTime(loc.opening_time)} – ${formatTime(loc.closing_time)}`, closed: false }];
    }
    return [];
  }
  const sorted = [...loc.schedules].sort((a, b) => a.day_of_week - b.day_of_week);
  if (sorted.every(s => !s.is_open)) return [{ days: 'All days', hours: 'Closed', closed: true }];

  const groups: { startDay: number; endDay: number; hours: string; closed: boolean }[] = [];
  for (const s of sorted) {
    const hrs = s.is_open ? `${formatTime(s.open_time)} – ${formatTime(s.close_time)}` : 'Closed';
    const last = groups[groups.length - 1];
    if (last && last.hours === hrs && last.endDay === s.day_of_week - 1) {
      last.endDay = s.day_of_week;
    } else {
      groups.push({ startDay: s.day_of_week, endDay: s.day_of_week, hours: hrs, closed: !s.is_open });
    }
  }

  return groups.map(g => ({
    days: g.startDay === g.endDay
      ? DAY_NAMES[g.startDay]
      : `${DAY_NAMES[g.startDay]}–${DAY_NAMES[g.endDay]}`,
    hours: g.hours,
    closed: g.closed,
  }));
}

export default function HoursDisplay({ location }: { location: Location }) {
  const groups = getGroupedHours(location);

  if (groups.length === 0) {
    return (
      <div className="flex items-center gap-3 text-sm text-muted-foreground">
        <Clock className="w-4 h-4 shrink-0 text-primary" />
        —
      </div>
    );
  }

  if (groups.length === 1 && !groups[0].closed) {
    return (
      <div className="flex items-center gap-3 text-sm text-muted-foreground">
        <Clock className="w-4 h-4 shrink-0 text-primary" />
        {groups[0].days}: {groups[0].hours}
      </div>
    );
  }

  return (
    <div className="flex items-start gap-3 text-sm text-muted-foreground">
      <Clock className="w-4 h-4 shrink-0 text-primary mt-0.5" />
      <div className="space-y-0.5">
        {groups.map(g => (
          <div key={g.days} className="flex items-center gap-2 text-xs">
            <span className="w-[70px] font-medium text-foreground">{g.days}</span>
            <span className={g.closed ? 'text-red-500' : ''}>{g.hours}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
