'use client';

import { Plus, Trash2 } from 'lucide-react';

export interface ScheduleWindow {
  days: number[];
  start: string;
  end: string;
}

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

interface Props {
  value: ScheduleWindow[] | null;
  onChange: (next: ScheduleWindow[] | null) => void;
  helpText?: string;
}

/**
 * Reusable editor for the Task #291 schedule shape:
 *   [{ days: [0..6], start: "HH:MM", end: "HH:MM" }, ...]
 * Empty array / null means "always available". Times are stored / displayed
 * in 24-hour HH:MM and evaluated server-side in the branch's timezone.
 */
export default function SchedulePicker({ value, onChange, helpText }: Props) {
  const windows = value ?? [];

  const addWindow = () => {
    onChange([...(windows), { days: [1, 2, 3, 4, 5], start: '09:00', end: '22:00' }]);
  };

  const updateWindow = (idx: number, patch: Partial<ScheduleWindow>) => {
    const next = windows.map((w, i) => (i === idx ? { ...w, ...patch } : w));
    onChange(next);
  };

  const removeWindow = (idx: number) => {
    const next = windows.filter((_, i) => i !== idx);
    onChange(next.length === 0 ? null : next);
  };

  const toggleDay = (idx: number, day: number) => {
    const w = windows[idx];
    const days = w.days.includes(day) ? w.days.filter(d => d !== day) : [...w.days, day].sort();
    updateWindow(idx, { days });
  };

  return (
    <div className="space-y-3">
      {helpText && (
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{helpText}</p>
      )}

      {windows.length === 0 && (
        <div className="text-center py-4 rounded-xl border border-dashed" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--muted-foreground))' }}>
          <p className="text-xs">Always available — add a window to limit times.</p>
        </div>
      )}

      {windows.map((w, idx) => (
        <div key={idx} className="rounded-xl border p-3 space-y-2" style={{ borderColor: 'hsl(var(--border))' }}>
          <div className="flex flex-wrap gap-1">
            {DAY_LABELS.map((label, day) => {
              const active = w.days.includes(day);
              return (
                <button
                  key={day}
                  type="button"
                  onClick={() => toggleDay(idx, day)}
                  className="px-2 py-1 rounded-md text-xs font-medium border transition-colors"
                  style={{
                    borderColor: active ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                    backgroundColor: active ? 'hsl(var(--primary-light))' : 'transparent',
                    color: active ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
                  }}
                >
                  {label}
                </button>
              );
            })}
          </div>
          <div className="flex items-center gap-2">
            <div className="flex-1">
              <label className="label-base text-xs">Start</label>
              <input
                type="time"
                className="input-base text-xs py-1.5"
                value={w.start}
                onChange={e => updateWindow(idx, { start: e.target.value })}
              />
            </div>
            <div className="flex-1">
              <label className="label-base text-xs">End</label>
              <input
                type="time"
                className="input-base text-xs py-1.5"
                value={w.end}
                onChange={e => updateWindow(idx, { end: e.target.value })}
              />
            </div>
            <button
              type="button"
              className="btn-ghost p-1.5 mt-5"
              style={{ color: 'hsl(var(--danger))' }}
              onClick={() => removeWindow(idx)}
              title="Remove window"
            >
              <Trash2 size={14} />
            </button>
          </div>
          {w.start > w.end && (
            <p className="text-xs" style={{ color: 'hsl(var(--warning))' }}>
              Overnight window: ends at {w.end} the next day.
            </p>
          )}
        </div>
      ))}

      <button
        type="button"
        className="btn-ghost text-xs px-2 py-1 flex items-center gap-1"
        style={{ color: 'hsl(var(--primary))' }}
        onClick={addWindow}
      >
        <Plus size={13} /> Add time window
      </button>
    </div>
  );
}
