import { useMemo, useState } from "react";
import type { GameSliceSession, SliceFittedModule } from "../types";
import { DEFAULT_SLICE_MODULES } from "../gameSliceState";
import { metricLabel, sliceButton, slicePrimaryButton } from "./sliceStyles";

const SHIP_LIMITS = {
  high: 3,
  med: 3,
  low: 2,
  cpu: 120,
  power: 80,
} as const;

const AVAILABLE_MODULES: SliceFittedModule[] = [
  ...DEFAULT_SLICE_MODULES,
  { id: "zora-comms", name: "Comms Uplink", type: "ai", slot: "med", power: 10, cpu: 12, active: false },
  { id: "zora-market", name: "Market Scanner", type: "ai", slot: "med", power: 12, cpu: 18, active: false },
  { id: "zora-event", name: "Event Logger", type: "ai", slot: "low", power: 4, cpu: 10, active: false },
  { id: "railgun1", name: "150mm Railgun", type: "weapon", slot: "high", power: 18, cpu: 35, active: false },
];

export function SliceFittingService({
  session,
  onUpdate,
}: {
  session: GameSliceSession;
  onUpdate: (modules: SliceFittedModule[]) => void;
}) {
  const [draft, setDraft] = useState<SliceFittedModule[]>(session.fittedModules);
  const usage = useMemo(() => ({
    cpu: draft.reduce((sum, module) => sum + module.cpu, 0),
    power: draft.reduce((sum, module) => sum + module.power, 0),
  }), [draft]);

  const slotCount = (slot: SliceFittedModule["slot"]) => draft.filter((module) => module.slot === slot).length;
  const canFit = (module: SliceFittedModule) => {
    const slotLimit = SHIP_LIMITS[module.slot];
    return slotCount(module.slot) < slotLimit && usage.cpu + module.cpu <= SHIP_LIMITS.cpu && usage.power + module.power <= SHIP_LIMITS.power;
  };
  const addModule = (module: SliceFittedModule) => {
    if (!canFit(module)) return;
    setDraft((prev) => [...prev, { ...module, id: `${module.id}-${Date.now().toString(36)}` }]);
  };

  return (
    <div style={{ display: "grid", gap: 12 }}>
      <div>
        <div style={metricLabel}>Merlin Fitting Console</div>
        <h2 style={{ margin: "6px 0 0", color: "#f8fafc", fontSize: 20, letterSpacing: 0 }}>Fitting</h2>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, fontFamily: "var(--font-mono)", fontSize: 11 }}>
        <span style={{ color: usage.cpu > SHIP_LIMITS.cpu ? "#ef4444" : "#22d3ee" }}>CPU {usage.cpu}/{SHIP_LIMITS.cpu}</span>
        <span style={{ color: usage.power > SHIP_LIMITS.power ? "#ef4444" : "#22c55e" }}>PWR {usage.power}/{SHIP_LIMITS.power}</span>
      </div>
      <div style={{ display: "grid", gap: 8 }}>
        <div style={metricLabel}>Fitted Modules</div>
        {draft.map((module, index) => (
          <button key={`${module.id}-${index}`} style={{ ...sliceButton, textAlign: "left" }} onClick={() => setDraft((prev) => prev.filter((_, itemIndex) => itemIndex !== index))}>
            {module.slot.toUpperCase()} · {module.name} · {module.cpu} CPU / {module.power} PWR
          </button>
        ))}
      </div>
      <div style={{ display: "grid", gap: 8 }}>
        <div style={metricLabel}>Available</div>
        {AVAILABLE_MODULES.map((module) => (
          <button key={module.id} style={{ ...sliceButton, textAlign: "left", opacity: canFit(module) ? 1 : 0.55 }} disabled={!canFit(module)} onClick={() => addModule(module)}>
            {module.slot.toUpperCase()} · {module.name}
          </button>
        ))}
      </div>
      <button style={slicePrimaryButton} onClick={() => onUpdate(draft)}>Confirm Fit</button>
    </div>
  );
}
