"use client";

import { useEffect, useState } from "react";
import { useCreator } from "../CreatorContext";
import SelectorGrid from "../components/SelectorGrid";
import Modal from "../components/Modal";
import ClassBuilder from "../components/ClassBuilder";

export default function ClassStep() {
  const { classes, refreshClasses, draft, update } = useCreator();
  const [builderOpen, setBuilderOpen] = useState(false);

  useEffect(() => { refreshClasses(); }, [refreshClasses]);

  const selectedClassId = draft.classes[0]?.classId;

  const selectClass = (classId: string) => {
    update({
      classes: [{ classId, level: draft.classes[0]?.level ?? 1 }],
    });
  };

  const setLevel = (level: number) => {
    if (!draft.classes[0]) return;
    update({ classes: [{ ...draft.classes[0], level }] });
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold text-neutral-100">Choose a Class</h2>
        <p className="text-sm text-neutral-400 mt-1">Multi-classing planned for later. Pick one for now.</p>
      </div>

      {selectedClassId && (
        <div className="flex items-center gap-3 p-3 bg-neutral-800/60 rounded border border-neutral-700">
          <label className="text-sm text-neutral-300">Starting level:</label>
          <input
            type="number"
            min={1}
            max={20}
            value={draft.classes[0]?.level ?? 1}
            onChange={(e) => setLevel(Math.max(1, Math.min(20, Number(e.target.value) || 1)))}
            className="w-20 bg-neutral-950 border border-neutral-700 rounded px-2 py-1 text-sm"
          />
        </div>
      )}

      <SelectorGrid
        items={classes}
        selectedId={selectedClassId}
        onSelect={(c) => selectClass(c.id)}
        onAddCustom={() => setBuilderOpen(true)}
        addLabel="Add Class"
        renderMeta={(c) => `d${c.hitDice?.sides ?? "?"} hit die`}
      />

      <Modal open={builderOpen} onClose={() => setBuilderOpen(false)} title="Create Custom Class" wide confirmClose>
        <ClassBuilder
          onCancel={() => setBuilderOpen(false)}
          onSave={async (c) => {
            await refreshClasses();
            selectClass(c.id);
            setBuilderOpen(false);
          }}
        />
      </Modal>
    </div>
  );
}
