import { clsx } from "clsx";
import type { StaffingRequirement } from "@capakraken/shared";
import { trpc } from "~/lib/trpc/client.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { SkillTagInput } from "~/components/ui/SkillTagInput.js";
import { formatCents } from "~/lib/format.js";
import { makeReq, type WizardState } from "./types.js";

interface Step3Props {
  state: WizardState;
  onChange: (patch: Partial<WizardState>) => void;
}

export function Step3Staffing({ state, onChange }: Step3Props) {
  const { data: rolesData } = trpc.role.list.useQuery({ isActive: true }, { staleTime: 30_000 });
  const roles = rolesData ?? [];

  const { data: chaptersData } = trpc.resource.chapters.useQuery(undefined, { staleTime: 60_000 });
  const chapters = (chaptersData ?? []) as string[];

  function updateReq(idx: number, patch: Partial<StaffingRequirement>) {
    const next = state.staffingReqs.map((r, i) => (i === idx ? { ...r, ...patch } : r));
    onChange({ staffingReqs: next });
  }

  function addReq() {
    onChange({ staffingReqs: [...state.staffingReqs, makeReq()] });
  }

  function removeReq(idx: number) {
    onChange({ staffingReqs: state.staffingReqs.filter((_, i) => i !== idx) });
  }

  return (
    <div>
      {state.blueprintId && state.staffingReqs.length > 0 && (
        <div className="mb-3 px-3 py-2 bg-brand-50 border border-brand-200 rounded-lg text-xs text-brand-700">
          Blueprint presets auto-loaded. Edit as needed.
        </div>
      )}

      {/* Budget allocation summary */}
      {state.budgetEur &&
        parseFloat(state.budgetEur) > 0 &&
        state.staffingReqs.length > 0 &&
        (() => {
          const projectBudgetCents = Math.round(parseFloat(state.budgetEur || "0") * 100);
          const allocatedCents = state.staffingReqs.reduce(
            (sum, r) => sum + (r.budgetCents ?? 0),
            0,
          );
          const remainingCents = projectBudgetCents - allocatedCents;
          const pct =
            projectBudgetCents > 0 ? Math.round((allocatedCents / projectBudgetCents) * 100) : 0;
          return (
            <div
              className={`mb-3 rounded-lg border p-3 text-xs ${remainingCents < 0 ? "bg-red-50 dark:bg-red-950/30 border-red-200 dark:border-red-800 text-red-700 dark:text-red-400" : remainingCents === 0 ? "bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800 text-green-700 dark:text-green-400" : "bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800 text-amber-700 dark:text-amber-300"}`}
            >
              <div className="flex items-center justify-between mb-1.5">
                <span className="font-semibold">Budget Allocation</span>
                <span>{pct}% allocated</span>
              </div>
              <div className="w-full h-1.5 bg-gray-200 rounded-full overflow-hidden mb-1.5">
                <div
                  className={`h-full rounded-full transition-all ${remainingCents < 0 ? "bg-red-500" : remainingCents === 0 ? "bg-green-500" : "bg-amber-500"}`}
                  style={{ width: `${Math.min(100, pct)}%` }}
                />
              </div>
              <div className="flex justify-between">
                <span>Project: {formatCents(projectBudgetCents)} EUR</span>
                <span>Allocated: {formatCents(allocatedCents)} EUR</span>
                <span className="font-semibold">Remaining: {formatCents(remainingCents)} EUR</span>
              </div>
            </div>
          );
        })()}

      <div className="space-y-3 max-h-[45vh] overflow-y-auto pr-1">
        {state.staffingReqs.length === 0 && (
          <p className="text-sm text-gray-400 text-center py-8">
            No requirements yet. Click &ldquo;+ Add Role&rdquo; to define staffing needs.
          </p>
        )}
        {state.staffingReqs.map((req, idx) => (
          <div key={req.id} className="border border-gray-200 rounded-lg p-3 bg-white">
            <div className="flex flex-wrap items-start gap-2">
              <div className="flex-1 min-w-32">
                <label className="text-xs text-gray-400">
                  Role *
                  <InfoTooltip content="Select a predefined role or enter a custom role name. Defines the skill profile for this staffing demand." />
                </label>
                {roles.length > 0 ? (
                  <select
                    value={req.roleId ?? ""}
                    onChange={(e) => {
                      const selectedId = e.target.value;
                      const matched = roles.find((ro) => ro.id === selectedId);
                      if (selectedId && matched) {
                        updateReq(idx, { roleId: matched.id, role: matched.name });
                      } else {
                        const { roleId: _r, ...rest } = state.staffingReqs[idx]!;
                        void _r;
                        onChange({
                          staffingReqs: state.staffingReqs.map((r, i) => (i === idx ? rest : r)),
                        });
                      }
                    }}
                    className="app-select w-full"
                  >
                    <option value="">Custom / Free text…</option>
                    {roles.map((ro) => (
                      <option key={ro.id} value={ro.id}>
                        {ro.name}
                      </option>
                    ))}
                  </select>
                ) : null}
                {!req.roleId && (
                  <input
                    type="text"
                    value={req.role}
                    onChange={(e) => updateReq(idx, { role: e.target.value })}
                    placeholder="e.g. 3D Artist"
                    className={clsx("app-input", roles.length > 0 && "mt-1")}
                  />
                )}
              </div>
              <div className="w-20">
                <label className="text-xs text-gray-400">
                  h/day
                  <InfoTooltip content="Planned working hours per day for this role." />
                </label>
                <input
                  type="number"
                  value={req.hoursPerDay}
                  min={0}
                  max={24}
                  step={0.5}
                  onChange={(e) => updateReq(idx, { hoursPerDay: parseFloat(e.target.value) || 0 })}
                  className="app-input"
                />
              </div>
              <div className="w-16">
                <label className="text-xs text-gray-400">
                  Count
                  <InfoTooltip content="Number of people needed for this role. Unfilled seats become placeholder demands until assigned." />
                </label>
                <input
                  type="number"
                  value={req.headcount}
                  min={1}
                  max={20}
                  onChange={(e) => updateReq(idx, { headcount: parseInt(e.target.value, 10) || 1 })}
                  className="app-input"
                />
              </div>
              <div className="w-28">
                <label className="text-xs text-gray-400">
                  Budget (EUR)
                  <InfoTooltip content="Optional budget cap for this role. Tracked against actual assignment costs." />
                </label>
                <input
                  type="number"
                  value={req.budgetCents ? req.budgetCents / 100 : ""}
                  min={0}
                  step={100}
                  onChange={(e) => {
                    const val = parseFloat(e.target.value);
                    updateReq(idx, {
                      budgetCents: Number.isFinite(val) && val > 0 ? Math.round(val * 100) : 0,
                    } as Partial<StaffingRequirement>);
                  }}
                  placeholder="0"
                  className="app-input"
                />
              </div>
              <div className="pt-5">
                <button
                  type="button"
                  onClick={() => removeReq(idx)}
                  className="app-action-danger-btn"
                >
                  ×
                </button>
              </div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2">
              <div>
                <label className="text-xs text-gray-400">
                  Required skills
                  <InfoTooltip content="Skills a resource must have to be suggested for this role." />
                </label>
                <SkillTagInput
                  value={req.requiredSkills}
                  onChange={(skills) => updateReq(idx, { requiredSkills: skills })}
                  placeholder="Add required skill…"
                />
              </div>
              <div>
                <label className="text-xs text-gray-400">
                  Preferred skills (optional)
                  <InfoTooltip content="Nice-to-have skills that boost a resource's match score but are not mandatory." />
                </label>
                <SkillTagInput
                  value={req.preferredSkills ?? []}
                  onChange={(skills) => updateReq(idx, { preferredSkills: skills })}
                  placeholder="Add preferred skill…"
                />
              </div>
              <div>
                <label className="text-xs text-gray-400">
                  Chapter filter (optional)
                  <InfoTooltip content="Restrict suggestions to resources from a specific chapter/department." />
                </label>
                <input
                  type="text"
                  list="chapter-options"
                  value={req.chapter ?? ""}
                  onChange={(e) =>
                    updateReq(idx, {
                      chapter: e.target.value || undefined,
                    } as Partial<StaffingRequirement>)
                  }
                  placeholder="e.g. Art Direction"
                  className="app-input"
                />
                {chapters.length > 0 && (
                  <datalist id="chapter-options">
                    {chapters.map((ch) => (
                      <option key={ch} value={ch} />
                    ))}
                  </datalist>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      <button
        type="button"
        onClick={addReq}
        className="mt-3 flex items-center gap-1.5 text-sm text-brand-600 hover:text-brand-800 font-medium"
      >
        <span className="text-lg leading-none">+</span> Add Role
      </button>
    </div>
  );
}
