import { formatDate, formatDateTime, formatDuration, formatTime, kindColor, kindLabel } from "./editorPresentation";
import type {
  EditorGroundStation,
  EditorMode,
  EditorTarget,
  EditorVisibilityWindow,
  EditorWork,
  EditorWorkPatch
} from "./model/editorTypes";

export type DownlinkSelection = {
  station: EditorGroundStation;
  pass: EditorVisibilityWindow;
};

export type DownlinkStationOption = {
  station: EditorGroundStation;
  passes: EditorVisibilityWindow[];
};

type WorkInspectorProps = {
  work: EditorWork;
  modes: EditorMode[];
  stations: EditorGroundStation[];
  conflicts: string[];
  onUpdate: (workId: string, patch: EditorWorkPatch) => void;
  onDelete: (workId: string) => void;
  onDuplicate: (workId: string) => void;
  onClose: () => void;
};

type ShootPanelProps = {
  target?: EditorTarget;
  passes: EditorVisibilityWindow[];
  selectedPass?: EditorVisibilityWindow;
  modeId?: string;
  modes: EditorMode[];
  onSelectPass: (pass?: EditorVisibilityWindow) => void;
  onModeChange: (modeId: string) => void;
  onAdd: () => void;
  onClose: () => void;
  onClearTarget: () => void;
};

type DownlinkPanelProps = {
  stationOptions: DownlinkStationOption[];
  selected?: DownlinkSelection;
  onSelect: (selection?: DownlinkSelection) => void;
  onAdd: () => void;
  onClose: () => void;
};

export function WorkInspector({
  work,
  modes,
  stations,
  conflicts,
  onUpdate,
  onDelete,
  onDuplicate,
  onClose
}: WorkInspectorProps) {
  const color = kindColor(work.kind);

  return (
    <div className="tgu-editor-panel">
      <PanelHead title={kindLabel(work.kind)} onClose={onClose} />
      <div className="tgu-editor-panel__id">{work.id}</div>

      {conflicts.length > 0 && (
        <div className="tgu-alert tgu-alert--warning">
          {conflicts.map((conflict) => (
            <div key={conflict}>{conflict}</div>
          ))}
        </div>
      )}

      <section className="tgu-editor-panel__section">
        <div className="tgu-editor-eyebrow">Время</div>
        <TimeStepper label="начало" value={work.startMs} max={work.endMs - 60_000} onChange={(value) => onUpdate(work.id, { startMs: value })} />
        <TimeStepper label="конец" value={work.endMs} min={work.startMs + 60_000} onChange={(value) => onUpdate(work.id, { endMs: value })} />
        <div className="tgu-editor-panel__hint">длительность: {formatDuration(work.endMs - work.startMs)}</div>
      </section>

      {work.kind === "shoot" && (
        <section className="tgu-editor-panel__section">
          <div className="tgu-editor-eyebrow">Режим аппаратуры</div>
          <div className="tgu-editor-chip-row">
            {modes.map((mode) => (
              <button
                className={work.modeId === mode.id ? "is-selected" : ""}
                key={mode.id}
                type="button"
                onClick={() => onUpdate(work.id, { modeId: mode.id, label: mode.label })}
              >
                {mode.label}
              </button>
            ))}
          </div>
          {work.targetName && <div className="tgu-editor-panel__hint">цель: {work.targetName}</div>}
        </section>
      )}

      {work.kind === "downlink" && (
        <section className="tgu-editor-panel__section">
          <div className="tgu-editor-eyebrow">Станция приёма</div>
          <select value={work.stationId ?? ""} onChange={(event) => onUpdate(work.id, { stationId: event.target.value })}>
            {stations.map((station) => (
              <option key={station.id} value={station.id}>
                {station.name}
              </option>
            ))}
          </select>
        </section>
      )}

      <div className="tgu-editor-panel__actions">
        <button className="tgu-button" type="button" onClick={() => onDuplicate(work.id)}>
          Дублировать
        </button>
        <button className="tgu-button tgu-button--reject" type="button" onClick={() => onDelete(work.id)}>
          Удалить
        </button>
      </div>

      <span className="tgu-editor-panel__color" style={{ background: color }} aria-hidden="true" />
    </div>
  );
}

export function ShootPanel({
  target,
  passes,
  selectedPass,
  modeId,
  modes,
  onSelectPass,
  onModeChange,
  onAdd,
  onClose,
  onClearTarget
}: ShootPanelProps) {
  return (
    <div className="tgu-editor-panel">
      <PanelHead title="Новая съёмка" onClose={onClose} />

      <section className="tgu-editor-panel__section">
        <div className="tgu-editor-panel__section-head">
          <div className="tgu-editor-eyebrow">1 · цель съёмки</div>
          {target && (
            <button className="tgu-link-button" type="button" onClick={onClearTarget}>
              сбросить
            </button>
          )}
        </div>
        {!target ? (
          <div className="tgu-editor-panel__placeholder">Кликните точку на карте слева, чтобы выбрать цель съёмки.</div>
        ) : (
          <div className="tgu-editor-target">
            <i />
            <span>{target.name}</span>
            <small>
              {target.lat.toFixed(2)}, {target.lon.toFixed(2)}
            </small>
          </div>
        )}
      </section>

      {target && (
        <section className="tgu-editor-panel__section">
          <div className="tgu-editor-eyebrow">2 · окно видимости</div>
          {passes.length === 0 ? (
            <div className="tgu-editor-panel__hint">В окне планирования проходов над целью нет.</div>
          ) : (
            <div className="tgu-editor-pass-list">
              {passes.map((pass) => {
                const selected = selectedPass?.startMs === pass.startMs && selectedPass.endMs === pass.endMs;
                return (
                  <button
                    className={selected ? "is-selected" : ""}
                    key={`${pass.startMs}-${pass.endMs}`}
                    type="button"
                    onClick={() => onSelectPass(pass)}
                  >
                    <span>{formatDate(pass.startMs)} {formatTime(pass.startMs)}</span>
                    <small>{formatDuration(pass.endMs - pass.startMs)}</small>
                  </button>
                );
              })}
            </div>
          )}
        </section>
      )}

      {target && selectedPass && (
        <section className="tgu-editor-panel__section">
          <div className="tgu-editor-eyebrow">3 · режим съёмки</div>
          <div className="tgu-editor-chip-row">
            {modes.map((mode) => (
              <button className={modeId === mode.id ? "is-selected" : ""} key={mode.id} type="button" onClick={() => onModeChange(mode.id)}>
                {mode.label}
              </button>
            ))}
          </div>
        </section>
      )}

      <button className="tgu-button tgu-button--primary" type="button" onClick={onAdd} disabled={!target || !selectedPass || !modeId}>
        + Добавить съёмку в план
      </button>
    </div>
  );
}

export function DownlinkPanel({ stationOptions, selected, onSelect, onAdd, onClose }: DownlinkPanelProps) {
  return (
    <div className="tgu-editor-panel">
      <PanelHead title="Новый сброс на НКПОР" onClose={onClose} />
      <div className="tgu-editor-panel__hint">Выберите станцию и сеанс связи для добавления сброса в черновик.</div>

      <div className="tgu-editor-station-list">
        {stationOptions.map((option) => (
          <div className="tgu-editor-station" key={option.station.id}>
            <div className="tgu-editor-station__head">
              <span>{option.station.name}</span>
              <small>{option.passes.length} сеанс.</small>
            </div>
            {option.passes.length === 0 ? (
              <div className="tgu-editor-panel__hint">нет сеансов в текущем окне</div>
            ) : (
              option.passes.slice(0, 5).map((pass) => {
                const isSelected = selected?.station.id === option.station.id && selected.pass.startMs === pass.startMs;
                return (
                  <button
                    className={isSelected ? "is-selected" : ""}
                    key={`${option.station.id}-${pass.startMs}`}
                    type="button"
                    onClick={() => onSelect({ station: option.station, pass })}
                  >
                    <span>{formatDateTime(pass.startMs)}-{formatTime(pass.endMs)}</span>
                    <small>{formatDuration(pass.endMs - pass.startMs)}</small>
                  </button>
                );
              })
            )}
          </div>
        ))}
      </div>

      <button className="tgu-button tgu-button--primary" type="button" onClick={onAdd} disabled={!selected}>
        + Добавить сброс в план
      </button>
    </div>
  );
}

function PanelHead({ title, onClose }: { title: string; onClose: () => void }) {
  return (
    <div className="tgu-editor-panel__head">
      <h2>{title}</h2>
      <button className="tgu-icon-button" type="button" onClick={onClose} title="Закрыть">
        ×
      </button>
    </div>
  );
}

function TimeStepper({
  label,
  value,
  min,
  max,
  onChange
}: {
  label: string;
  value: number;
  min?: number;
  max?: number;
  onChange: (value: number) => void;
}) {
  const change = (deltaMs: number) => {
    const next = Math.max(min ?? Number.NEGATIVE_INFINITY, Math.min(max ?? Number.POSITIVE_INFINITY, value + deltaMs));
    onChange(next);
  };

  return (
    <label className="tgu-editor-time-stepper">
      <span>{label}</span>
      <div>
        <button type="button" onClick={() => change(-3_600_000)}>−ч</button>
        <button type="button" onClick={() => change(-5 * 60_000)}>−5м</button>
        <output>{formatDateTime(value)}</output>
        <button type="button" onClick={() => change(5 * 60_000)}>+5м</button>
        <button type="button" onClick={() => change(3_600_000)}>+ч</button>
      </div>
    </label>
  );
}
