"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import type { Procedure } from "@/data/consentiq/procedures";
import { Button } from "@/components/Button";
import { DraftBanner } from "@/components/consentiq/DraftBanner";
import {
  ConsentDocument,
  type BuilderValues,
  type PatientDetails,
} from "@/components/consentiq/ConsentDocument";

type Step = 1 | 2 | 3;

const steps: Array<{ n: Step; label: string; help: string }> = [
  { n: 1, label: "Patient", help: "Identifying details" },
  { n: 2, label: "Procedure options", help: "Approach, side, implants" },
  { n: 3, label: "Review", help: "Generated consent preview" },
];

export function BuilderWizard({ procedure }: { procedure: Procedure }) {
  const [step, setStep] = useState<Step>(1);

  const [patient, setPatient] = useState<PatientDetails>({
    fullName: "",
    dob: "",
    mrn: "",
    languagePref: "English",
  });

  const initialValues = useMemo<BuilderValues>(() => {
    const v: BuilderValues = {};
    for (const opt of procedure.options) {
      if (opt.defaultValue) v[opt.id] = opt.defaultValue;
    }
    return v;
  }, [procedure]);

  const [values, setValues] = useState<BuilderValues>(initialValues);

  const canAdvance1 =
    patient.fullName.trim().length > 0 &&
    patient.dob.trim().length > 0 &&
    patient.mrn.trim().length > 0;

  const canAdvance2 = procedure.options.every(
    (o) => values[o.id] && values[o.id].length > 0,
  );

  const print = () => {
    if (typeof window !== "undefined") window.print();
  };

  return (
    <div>
      <DraftBanner className="mb-8" />

      {/* Stepper */}
      <ol className="mb-10 flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-0">
        {steps.map((s, i) => {
          const active = step === s.n;
          const done = step > s.n;
          return (
            <li key={s.n} className="flex flex-1 items-center gap-3">
              <button
                type="button"
                onClick={() => {
                  if (s.n === 1) setStep(1);
                  if (s.n === 2 && canAdvance1) setStep(2);
                  if (s.n === 3 && canAdvance1 && canAdvance2) setStep(3);
                }}
                className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-[14px] font-bold transition-colors ${
                  active
                    ? "bg-[var(--color-blue)] text-white"
                    : done
                      ? "bg-[var(--color-blue-deep)] text-white"
                      : "bg-[var(--color-mist)] text-[var(--color-slate)]"
                }`}
                aria-current={active ? "step" : undefined}
              >
                {s.n}
              </button>
              <div className="flex-1">
                <div
                  className={`text-[13px] font-bold uppercase tracking-wider ${
                    active ? "text-[var(--color-blue)]" : "text-[var(--color-slate)]"
                  }`}
                >
                  {s.label}
                </div>
                <div className="text-[12px] text-[var(--color-slate)]">
                  {s.help}
                </div>
              </div>
              {i < steps.length - 1 && (
                <div className="hidden h-px flex-1 bg-[var(--color-line)] sm:block" />
              )}
            </li>
          );
        })}
      </ol>

      {step === 1 && (
        <section className="rounded-xl border border-[var(--color-line)] bg-white p-6 md:p-8">
          <h2 className="font-display text-[22px] font-bold tracking-tight text-[var(--color-ink)]">
            Patient details
          </h2>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            Nothing is submitted or stored — values stay in the browser.
          </p>

          <div className="mt-6 grid gap-5 md:grid-cols-2">
            <Field
              label="Full name"
              required
              value={patient.fullName}
              onChange={(v) => setPatient((p) => ({ ...p, fullName: v }))}
              placeholder="e.g. Jane Doe"
            />
            <Field
              label="Date of birth"
              required
              type="date"
              value={patient.dob}
              onChange={(v) => setPatient((p) => ({ ...p, dob: v }))}
            />
            <Field
              label="MRN / Hospital number"
              required
              value={patient.mrn}
              onChange={(v) => setPatient((p) => ({ ...p, mrn: v }))}
              placeholder="e.g. 1234567"
            />
            <div>
              <label className="block text-[13px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                Language preference
              </label>
              <select
                value={patient.languagePref}
                onChange={(e) =>
                  setPatient((p) => ({ ...p, languagePref: e.target.value }))
                }
                className="mt-2 w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-3 text-[15px] text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20"
              >
                {[
                  "English",
                  "Arabic",
                  "French",
                  "Spanish",
                  "Urdu",
                  "Polish",
                  "Other",
                ].map((l) => (
                  <option key={l}>{l}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="mt-8 flex justify-end">
            <Button
              onClick={() => canAdvance1 && setStep(2)}
              variant="primary"
              className={canAdvance1 ? "" : "cursor-not-allowed opacity-50"}
            >
              Continue to procedure options →
            </Button>
          </div>
        </section>
      )}

      {step === 2 && (
        <section className="rounded-xl border border-[var(--color-line)] bg-white p-6 md:p-8">
          <h2 className="font-display text-[22px] font-bold tracking-tight text-[var(--color-ink)]">
            {procedure.name} · options
          </h2>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            These options adapt the generated document — for example the
            approach, laterality, and implant type. Only options defined for
            this procedure are shown.
          </p>

          <div className="mt-6 space-y-6">
            {procedure.options.map((opt) => (
              <div key={opt.id}>
                <label className="block text-[13px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                  {opt.label}
                </label>
                {opt.help && (
                  <div className="mt-1 text-[12px] text-[var(--color-slate)]">
                    {opt.help}
                  </div>
                )}

                {opt.kind === "radio" && opt.choices && (
                  <div className="mt-3 flex flex-wrap gap-2">
                    {opt.choices.map((c) => {
                      const active = values[opt.id] === c.value;
                      return (
                        <button
                          type="button"
                          key={c.value}
                          onClick={() =>
                            setValues((v) => ({ ...v, [opt.id]: c.value }))
                          }
                          className={`rounded-full border px-4 py-2 text-[13px] font-semibold transition-colors ${
                            active
                              ? "border-[var(--color-blue)] bg-[var(--color-blue)] text-white"
                              : "border-[var(--color-line)] bg-white text-[var(--color-slate)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                          }`}
                        >
                          {c.label}
                        </button>
                      );
                    })}
                  </div>
                )}

                {opt.kind === "select" && opt.choices && (
                  <select
                    value={values[opt.id] ?? ""}
                    onChange={(e) =>
                      setValues((v) => ({ ...v, [opt.id]: e.target.value }))
                    }
                    className="mt-3 w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-3 text-[15px] text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20 md:max-w-md"
                  >
                    <option value="" disabled>
                      Choose...
                    </option>
                    {opt.choices.map((c) => (
                      <option key={c.value} value={c.value}>
                        {c.label}
                      </option>
                    ))}
                  </select>
                )}

                {opt.kind === "text" && (
                  <input
                    type="text"
                    value={values[opt.id] ?? ""}
                    onChange={(e) =>
                      setValues((v) => ({ ...v, [opt.id]: e.target.value }))
                    }
                    className="mt-3 w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-3 text-[15px] text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20 md:max-w-md"
                  />
                )}
              </div>
            ))}
          </div>

          <div className="mt-8 flex items-center justify-between gap-3">
            <button
              type="button"
              onClick={() => setStep(1)}
              className="text-[14px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-ink)]"
            >
              ← Back
            </button>
            <Button
              onClick={() => canAdvance2 && setStep(3)}
              variant="primary"
              className={canAdvance2 ? "" : "cursor-not-allowed opacity-50"}
            >
              Generate preview →
            </Button>
          </div>
        </section>
      )}

      {step === 3 && (
        <section>
          <div className="mb-6 flex flex-wrap items-center justify-between gap-3 print:hidden">
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => setStep(2)}
                className="text-[14px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-ink)]"
              >
                ← Edit options
              </button>
              <span className="text-[var(--color-line)]">|</span>
              <button
                type="button"
                onClick={() => setStep(1)}
                className="text-[14px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-ink)]"
              >
                Edit patient details
              </button>
            </div>
            <Button onClick={print} variant="primary">
              Print / Save as PDF
            </Button>
          </div>

          <ConsentDocument
            procedure={procedure}
            patient={patient}
            values={values}
          />

          <div className="mt-8 text-center text-[13px] text-[var(--color-slate)] print:hidden">
            <Link
              href="/products/consentiq/procedures"
              className="font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
            >
              ← Choose a different procedure
            </Link>
          </div>
        </section>
      )}
    </div>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  placeholder,
  required,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
  placeholder?: string;
  required?: boolean;
}) {
  return (
    <div>
      <label className="block text-[13px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {label}
        {required && <span className="ml-1 text-[var(--color-blue)]">*</span>}
      </label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="mt-2 w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-3 text-[15px] text-[var(--color-ink)] placeholder:text-[var(--color-slate)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20"
      />
    </div>
  );
}
