import { ArrowLeft, Gift, Loader2, WandSparkles } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';

import type { CreateBabyObjectMatchDraftRequest } from '../../../packages/shared/src/contracts/edutainmentBabyObject';
import { validateBabyObjectMatchItemNames } from '../../../packages/shared/src/contracts/edutainmentBabyObject';
import { PlatformActionButton } from '../common/PlatformActionButton';
import { PlatformFieldLabel } from '../common/PlatformFieldLabel';
import { PlatformIconBadge } from '../common/PlatformIconBadge';
import { PlatformPillBadge } from '../common/PlatformPillBadge';
import { PlatformStatusMessage } from '../common/PlatformStatusMessage';
import { PlatformSubpanel } from '../common/PlatformSubpanel';
import { PlatformTextField } from '../common/PlatformTextField';

type BabyObjectMatchWorkspaceProps = {
  isBusy?: boolean;
  error?: string | null;
  initialPayload?: CreateBabyObjectMatchDraftRequest | null;
  onBack: () => void;
  onCreateDraft: (payload: CreateBabyObjectMatchDraftRequest) => void;
  showBackButton?: boolean;
  title?: string | null;
};

type BabyObjectMatchFormState = {
  itemAName: string;
  itemBName: string;
};

function resolveInitialFormState(
  initialPayload: CreateBabyObjectMatchDraftRequest | null | undefined,
): BabyObjectMatchFormState {
  return {
    itemAName: initialPayload?.itemAName ?? '',
    itemBName: initialPayload?.itemBName ?? '',
  };
}

export function BabyObjectMatchWorkspace({
  isBusy = false,
  error = null,
  initialPayload = null,
  onBack,
  onCreateDraft,
  showBackButton = true,
  title = null,
}: BabyObjectMatchWorkspaceProps) {
  const [formState, setFormState] = useState<BabyObjectMatchFormState>(() =>
    resolveInitialFormState(initialPayload),
  );
  const appliedInitialKeyRef = useRef<string | null>(null);

  useEffect(() => {
    const nextInitialKey = JSON.stringify(initialPayload ?? null);
    if (appliedInitialKeyRef.current === nextInitialKey) {
      return;
    }

    appliedInitialKeyRef.current = nextInitialKey;
    setFormState(resolveInitialFormState(initialPayload));
  }, [initialPayload]);

  const validation = useMemo(
    () => validateBabyObjectMatchItemNames(formState),
    [formState],
  );
  const canSubmit = validation.valid && !isBusy;

  const submitForm = () => {
    if (!canSubmit) {
      return;
    }

    onCreateDraft({
      itemAName: validation.itemAName,
      itemBName: validation.itemBName,
    });
  };

  return (
    <div className="platform-remap-surface mx-auto flex h-full min-h-0 w-full max-w-5xl flex-col overflow-hidden">
      {showBackButton ? (
        <div className="mb-3 flex shrink-0 items-center justify-between gap-3 sm:mb-4">
          <PlatformActionButton
            onClick={onBack}
            disabled={isBusy}
            tone="ghost"
            size="xs"
            className="min-h-0 self-start gap-1.5 px-3 py-1.5 text-[11px]"
          >
            <ArrowLeft className="h-3.5 w-3.5" />
            返回
          </PlatformActionButton>
        </div>
      ) : null}

      <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
        {title ? (
          <div className="mb-3 shrink-0 sm:mb-5">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="m-0 text-3xl font-black leading-none tracking-normal text-[var(--platform-text-strong)] sm:text-7xl">
                {title}
              </h1>
              <PlatformPillBadge tone="success" size="xs">
                BETA
              </PlatformPillBadge>
            </div>
          </div>
        ) : null}

        <section className="flex min-h-0 flex-1 flex-col overflow-hidden">
          <div
            className={`grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(14rem,0.56fr)] ${isBusy ? 'opacity-55' : ''}`}
          >
            <div className="grid min-h-0 gap-3 sm:grid-cols-2 lg:grid-cols-1">
              <label className="block min-h-0">
                <PlatformFieldLabel variant="form">物品 A</PlatformFieldLabel>
                <PlatformTextField
                  value={formState.itemAName}
                  disabled={isBusy}
                  placeholder=""
                  onChange={(event) =>
                    setFormState((current) => ({
                      ...current,
                      itemAName: event.target.value,
                    }))
                  }
                  size="lg"
                  density="roomy"
                  tone="emerald"
                  className="min-h-12 rounded-[1.05rem]"
                  aria-label="物品 A"
                />
              </label>
              <label className="block min-h-0">
                <PlatformFieldLabel variant="form">物品 B</PlatformFieldLabel>
                <PlatformTextField
                  value={formState.itemBName}
                  disabled={isBusy}
                  placeholder=""
                  onChange={(event) =>
                    setFormState((current) => ({
                      ...current,
                      itemBName: event.target.value,
                    }))
                  }
                  size="lg"
                  density="roomy"
                  tone="emerald"
                  className="min-h-12 rounded-[1.05rem]"
                  aria-label="物品 B"
                />
              </label>
            </div>

            <PlatformSubpanel
              as="div"
              surface="soft"
              radius="md"
              padding="md"
              className="relative min-h-[8rem] overflow-hidden bg-[linear-gradient(145deg,rgba(236,253,245,0.92),rgba(255,247,237,0.86))] shadow-[inset_0_1px_0_rgba(255,255,255,0.78)]"
            >
              <div className="absolute -right-8 -top-8 h-28 w-28 rounded-full bg-emerald-200/42" />
              <div className="absolute -bottom-10 left-6 h-24 w-24 rounded-full bg-amber-200/48" />
              <div className="relative flex h-full min-h-[7rem] flex-col items-center justify-center gap-3 text-center">
                <PlatformIconBadge
                  icon={<Gift className="h-7 w-7" />}
                  label="宝贝识物图标"
                  size="xl"
                  shape="rounded"
                  tone="softBright"
                  className="text-emerald-600 shadow-[0_12px_30px_rgba(16,185,129,0.14)]"
                />
                <div className="text-lg font-black text-[var(--platform-text-strong)]">
                  宝贝识物
                </div>
              </div>
            </PlatformSubpanel>
          </div>

          <div className="mt-2 shrink-0 space-y-3">
            {error ? (
              <PlatformStatusMessage
                tone="error"
                surface="platform"
                size="md"
                className="rounded-2xl"
              >
                {error}
              </PlatformStatusMessage>
            ) : null}
          </div>
        </section>
      </div>

      <div className="mt-2 flex shrink-0 justify-center pb-[max(0.25rem,env(safe-area-inset-bottom))] sm:mt-3">
        <PlatformActionButton
          disabled={!canSubmit}
          onClick={submitForm}
          className="min-h-10 gap-2 px-4 py-2 text-sm sm:min-h-11 sm:px-5"
        >
          {isBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          <WandSparkles className="h-4 w-4" />
          <span>生成宝贝识物草稿</span>
        </PlatformActionButton>
      </div>
    </div>
  );
}

export default BabyObjectMatchWorkspace;
