import * as React from "react";
import { useLocation } from "react-router-dom";
import {
  type OrgPickerEmbedOptions,
  type OrgPickerMode,
  type OrgPickerSelectableType,
  buildOrgPickerEmbedSrc,
  parseOrgPickerEmbedOptions,
} from "../pickerTypes";

type PickerMessage = {
  type: string;
  payload?: unknown;
  error?: string;
};

function PickerScenarioControls({
  options,
  onChange,
}: {
  options: OrgPickerEmbedOptions;
  onChange: (options: OrgPickerEmbedOptions) => void;
}) {
  return (
    <div className="grid gap-3 rounded-md border border-border bg-card p-4 md:grid-cols-2 lg:grid-cols-[1fr,1fr,1fr,auto,auto,auto,auto] lg:items-end">
      <label className="space-y-1 text-sm font-medium">
        <span className="block text-muted-foreground">선택 모드</span>
        <select
          className="h-10 w-full rounded-md border border-input bg-background px-3"
          value={options.mode}
          onChange={(event) =>
            onChange({
              ...options,
              mode: event.target.value as OrgPickerMode,
            })
          }
        >
          <option value="multiple">복수 선택</option>
          <option value="single">단일 선택</option>
        </select>
      </label>

      <label className="space-y-1 text-sm font-medium">
        <span className="block text-muted-foreground">선택 대상</span>
        <select
          className="h-10 w-full rounded-md border border-input bg-background px-3"
          value={options.select}
          onChange={(event) =>
            onChange({
              ...options,
              select: event.target.value as OrgPickerSelectableType,
            })
          }
        >
          <option value="both">조직&구성원</option>
          <option value="tenant">조직</option>
          <option value="user">구성원</option>
        </select>
      </label>

      <label className="space-y-1 text-sm font-medium">
        <span className="block text-muted-foreground">tenant slug</span>
        <input
          className="h-10 w-full rounded-md border border-input bg-background px-3"
          onChange={(event) =>
            onChange({
              ...options,
              tenantId: event.target.value,
            })
          }
          placeholder="saman"
          type="text"
          value={options.tenantId}
        />
      </label>

      <label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
        <input
          checked={options.includeDescendants}
          disabled={options.mode === "single"}
          onChange={(event) =>
            onChange({
              ...options,
              includeDescendants: event.target.checked,
            })
          }
          type="checkbox"
        />
        <span>하위 포함</span>
      </label>

      <label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
        <input
          checked={options.showDescendantToggle}
          disabled={options.mode === "single"}
          onChange={(event) =>
            onChange({
              ...options,
              showDescendantToggle: event.target.checked,
            })
          }
          type="checkbox"
        />
        <span>하위 선택 스위치 표시</span>
      </label>

      <label className="space-y-1 text-sm font-medium">
        <span className="block text-muted-foreground">임베딩 너비</span>
        <input
          className="h-10 w-full rounded-md border border-input bg-background px-3"
          min={240}
          max={1600}
          onChange={(event) =>
            onChange({
              ...options,
              width: Number.parseInt(event.target.value || "400", 10),
            })
          }
          type="number"
          value={options.width}
        />
      </label>

      <label className="space-y-1 text-sm font-medium">
        <span className="block text-muted-foreground">임베딩 높이</span>
        <input
          className="h-10 w-full rounded-md border border-input bg-background px-3"
          min={240}
          max={1600}
          onChange={(event) =>
            onChange({
              ...options,
              height: Number.parseInt(event.target.value || "600", 10),
            })
          }
          type="number"
          value={options.height}
        />
      </label>
    </div>
  );
}

export function OrgPickerEmbedPreviewPage() {
  const location = useLocation();
  const shareToken = new URLSearchParams(location.search).get("token");
  const [options, setOptions] = React.useState<OrgPickerEmbedOptions>(() =>
    parseOrgPickerEmbedOptions(location.search),
  );
  const [lastMessage, setLastMessage] = React.useState<PickerMessage | null>(
    null,
  );
  const pickerSrcBase = buildOrgPickerEmbedSrc(options);
  const pickerSrc = shareToken
    ? `${pickerSrcBase}&token=${encodeURIComponent(shareToken)}`
    : pickerSrcBase;

  React.useEffect(() => {
    const handleMessage = (event: MessageEvent<PickerMessage>) => {
      if (!event.data?.type?.startsWith("orgfront:picker:")) return;
      setLastMessage(event.data);
    };

    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, []);

  return (
    <div className="space-y-5">
      <header className="space-y-3">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
            Embed Preview
          </p>
          <h1 className="text-2xl font-semibold">임베딩 검증</h1>
        </div>
        <div
          className="min-h-16 w-full overflow-x-auto rounded-md border border-border bg-card px-4 py-3 font-mono text-sm leading-6 text-foreground"
          data-testid="embed-preview-src"
        >
          {pickerSrc}
        </div>
      </header>

      <PickerScenarioControls options={options} onChange={setOptions} />

      <section className="grid gap-4 lg:grid-cols-[1fr,360px]">
        <div
          className="max-w-full resize overflow-auto rounded-md border border-border bg-card"
          data-testid="embed-preview-frame-shell"
          style={{
            width: options.width,
            height: options.height,
          }}
        >
          <iframe
            className="h-full w-full bg-background"
            src={pickerSrc}
            title="조직 선택기 임베딩 검증"
          />
        </div>

        <aside className="space-y-3 rounded-md border border-border bg-card p-4">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
              postMessage
            </p>
            <h2 className="text-lg font-semibold">수신 결과</h2>
          </div>
          <pre
            className="min-h-[280px] overflow-auto rounded-md border border-border bg-background p-3 text-xs"
            data-testid="embed-preview-output"
          >
            {lastMessage
              ? JSON.stringify(lastMessage, null, 2)
              : "아직 수신된 메시지가 없습니다."}
          </pre>
        </aside>
      </section>
    </div>
  );
}
