import { X } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Field, SelectField, TextField } from "@/components/ui/Field";
import { Lookup } from "@/components/ui/Lookup";
import { fmtDate } from "@/lib/format";
import type { OpenPositionResolved } from "@/lib/positions";
import type { HireDraftData } from "./types";

type StepPositionProps = {
  draft: HireDraftData;
  update: (patch: Partial<HireDraftData>) => void;
  openPositions: OpenPositionResolved[];
};

export function StepPosition({ draft, update, openPositions }: StepPositionProps) {
  const selected = openPositions.find((p) => p.id === draft.positionId) ?? null;

  async function search(query: string): Promise<OpenPositionResolved[]> {
    const q = query.toLowerCase();
    return openPositions.filter((p) => p.title.toLowerCase().includes(q) || p.position_number.includes(q));
  }

  return (
    <div className="flex flex-col gap-4">
      {!selected ? (
        <Field
          label="Position"
          required
          hint={openPositions.length === 0 ? "Derzeit sind keine offenen Positionen vorhanden." : undefined}
        >
          {(p) => (
            <Lookup<OpenPositionResolved>
              {...p}
              placeholder="Positionsname oder -nummer…"
              onSearch={search}
              onSelect={(pos) => update({ positionId: pos.id })}
              renderResult={(pos) => (
                <div>
                  <div className="font-semibold text-ink">{pos.title}</div>
                  <div className="text-xs text-ink-muted">
                    {pos.position_number} · {pos.orgLabel}
                  </div>
                </div>
              )}
            />
          )}
        </Field>
      ) : (
        <div>
          <p className="mb-1 block text-sm font-semibold text-ink">Position</p>
          <div className="flex items-center justify-between rounded border border-border bg-surface p-3">
            <div>
              <div className="text-sm font-semibold text-ink">{selected.title}</div>
              <div className="text-xs text-ink-muted">
                {selected.position_number} · {selected.orgLabel}
              </div>
              <div className="text-xs text-ink-muted">Gültig ab {fmtDate(selected.valid_from)}</div>
            </div>
            <Button variant="icon" onClick={() => update({ positionId: "" })} aria-label="Auswahl aufheben">
              <X className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      <SelectField
        label="Besetzung"
        required
        value={draft.besetzung}
        onChange={(v) => update({ besetzung: v as HireDraftData["besetzung"] })}
        placeholder="Bitte wählen…"
        options={[
          { value: "Extern", label: "Extern" },
          { value: "Intern", label: "Intern" },
        ]}
      />

      <TextField
        label="Führungskraft"
        value={selected?.managerName ?? "–"}
        onChange={() => {}}
        disabled
        hint="Ergibt sich aus der gewählten Position."
      />
    </div>
  );
}
