"use client";

/**
 * SceneToGeneratorButton
 *
 * Tombol "→ Generate Prompt" per scene di StoryboardOutput.
 * Klik → tampilkan platform picker → confirm → pre-fill GeneratorForm
 * via sessionStorage + navigate ke /generator/[platform].
 */

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Wand2, X, ChevronRight, ArrowRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { PLATFORM_CONFIGS } from "@/types";
import type { Platform } from "@/types";
import type { StoryboardScene } from "@/types/storyboard";

// ── Mapping scene data → platform input fields ───────────────────────────────
//
// GeneratorForm reads from sessionStorage("template_input") and maps:
//   subject         ← visualDescription + narration
//   style           ← storyboard style hint
//   mood            ← scene emotion
//   sceneDescription ← full scene narration (Seedance advanced)
//   additionalContext ← narration (Gemini)
//   targetAudience   ← narration (TikTok)
//
function buildPrefillData(
  scene: StoryboardScene,
  platform: Platform,
  storyboardStyle: string
): Record<string, unknown> {
  const subject = [scene.visualDescription, scene.title]
    .filter(Boolean)
    .join(". ");

  const base: Record<string, unknown> = {
    subject,
    mood:     scene.emotion  ?? undefined,
    style:    storyboardStyle !== "social_media" && storyboardStyle !== "ugc"
                ? storyboardStyle
                : undefined,
    mode:     "advanced",
    language: "id",
    variations: 1,
  };

  switch (platform) {
    case "seedance":
      return {
        ...base,
        cameraAngle:      scene.cameraAngle ? normalizeCameraAngle(scene.cameraAngle) : undefined,
        sceneDescription: scene.narration ?? undefined,
        duration:         parseDurationToSeedance(scene.duration),
      };

    case "kling_motion":
      return {
        ...base,
        subjectMotion: "static",
      };

    case "higgsfield":
      return {
        ...base,
      };

    case "gemini_omni":
      return {
        ...base,
        outputType:        "video",
        additionalContext: scene.narration ?? undefined,
      };

    case "tiktok_ugc":
      return {
        ...base,
        // For TikTok, use narration as pain point context
        targetAudience: undefined,
        painPoint:      scene.narration ?? undefined,
        hookType:       "story",
      };

    default:
      return base;
  }
}

// Map free-text camera angle to Seedance enum values
function normalizeCameraAngle(angle: string): string | undefined {
  const a = angle.toLowerCase();
  if (a.includes("bird") || a.includes("aerial") || a.includes("atas")) return "bird_eye";
  if (a.includes("low") || a.includes("bawah") || a.includes("worm")) return "low_angle";
  if (a.includes("high") || a.includes("tinggi")) return "high_angle";
  if (a.includes("dutch") || a.includes("miring")) return "dutch_angle";
  if (a.includes("shoulder") || a.includes("belakang")) return "over_shoulder";
  return "eye_level"; // default
}

// Map duration string like "3-5 detik" → nearest Seedance preset
function parseDurationToSeedance(duration: string): string | undefined {
  if (!duration) return undefined;
  const match = duration.match(/(\d+)/);
  if (!match) return "5s";
  const secs = parseInt(match[1], 10);
  if (secs <= 3)  return "3s";
  if (secs <= 5)  return "5s";
  if (secs <= 8)  return "8s";
  return "10s";
}

// ── Platform list to show in picker ─────────────────────────────────────────
const PLATFORMS: Platform[] = [
  "seedance",
  "kling_motion",
  "higgsfield",
  "gemini_omni",
  "tiktok_ugc",
];

// ── Sub-component: Platform picker bottom sheet ──────────────────────────────
interface PlatformPickerProps {
  scene: StoryboardScene;
  storyboardStyle: string;
  onClose: () => void;
}

function PlatformPicker({ scene, storyboardStyle, onClose }: PlatformPickerProps) {
  const router = useRouter();
  const [selected, setSelected] = useState<Platform | null>(null);
  const [navigating, setNavigating] = useState(false);

  const handleConfirm = () => {
    if (!selected) return;
    setNavigating(true);

    const prefill = buildPrefillData(scene, selected, storyboardStyle);
    // Tambah metadata sumber untuk toast yang lebih informatif
    sessionStorage.setItem("scene_prefill", JSON.stringify({
      ...prefill,
      _source:      "storyboard_scene",
      _sceneNumber: scene.sceneNumber,
    }));

    router.push(`/generator/${selected}`);
  };

  return (
    // Backdrop
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/60 backdrop-blur-sm"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="w-full max-w-sm bg-background rounded-t-2xl sm:rounded-2xl border border-border shadow-2xl overflow-hidden animate-in slide-in-from-bottom-4 duration-200">

        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-border/60">
          <div>
            <p className="text-sm font-semibold">Generate Prompt</p>
            <p className="text-[11px] text-muted-foreground truncate max-w-[200px]">
              Scene {scene.sceneNumber}: {scene.title}
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-7 h-7 rounded-full bg-accent flex items-center justify-center hover:bg-accent/80 transition-colors"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>

        {/* Scene preview */}
        <div className="mx-4 my-3 p-3 rounded-xl bg-accent/60 border border-border/40">
          <p className="text-[10px] text-muted-foreground mb-1">Visual yang akan digenerate:</p>
          <p className="text-xs leading-relaxed line-clamp-3 text-foreground/90">
            {scene.visualDescription}
          </p>
          {scene.emotion && (
            <span className="mt-2 inline-flex items-center px-2 py-0.5 rounded-full bg-rose-500/10 text-rose-300 text-[10px]">
              💭 {scene.emotion}
            </span>
          )}
        </div>

        {/* Platform list */}
        <div className="px-4 pb-2 space-y-1.5">
          <p className="text-[11px] text-muted-foreground font-medium px-1">Pilih platform:</p>
          {PLATFORMS.map((p) => {
            const config = PLATFORM_CONFIGS[p];
            return (
              <button
                key={p}
                type="button"
                onClick={() => setSelected(p)}
                className={cn(
                  "w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border transition-all text-left",
                  selected === p
                    ? "border-primary bg-primary/10"
                    : "border-border/60 bg-accent/40 hover:border-primary/40 hover:bg-accent/60"
                )}
              >
                <span className="text-xl flex-shrink-0">{config.icon}</span>
                <div className="flex-1 min-w-0">
                  <div className="text-xs font-semibold leading-tight">{config.name}</div>
                  <div className="text-[10px] text-muted-foreground leading-tight truncate">
                    {config.description}
                  </div>
                </div>
                {selected === p && (
                  <ChevronRight className="w-4 h-4 text-primary flex-shrink-0" />
                )}
              </button>
            );
          })}
        </div>

        {/* Confirm button */}
        <div className="px-4 pb-4 pt-3">
          <button
            type="button"
            onClick={handleConfirm}
            disabled={!selected || navigating}
            className="w-full py-3 rounded-xl bg-gradient-to-r from-violet-600 to-blue-600 text-white text-sm font-semibold flex items-center justify-center gap-2 hover:opacity-90 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
          >
            {navigating ? (
              <>Membuka Generator...</>
            ) : (
              <>
                <ArrowRight className="w-4 h-4" />
                Buka Generator{selected ? ` — ${PLATFORM_CONFIGS[selected].name}` : ""}
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Main export ───────────────────────────────────────────────────────────────
interface Props {
  scene: StoryboardScene;
  storyboardStyle: string;
  /** Compact = ikon saja, full = ikon + teks */
  compact?: boolean;
}

export default function SceneToGeneratorButton({ scene, storyboardStyle, compact = false }: Props) {
  const [open, setOpen] = useState(false);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        title="Generate prompt untuk scene ini"
        className={cn(
          "flex items-center gap-1.5 rounded-lg border transition-all text-xs font-medium",
          "border-violet-500/30 bg-violet-500/8 text-violet-300 hover:bg-violet-500/15 hover:border-violet-500/50",
          compact ? "px-2 py-1" : "px-2.5 py-1.5"
        )}
      >
        <Wand2 className="w-3 h-3 flex-shrink-0" />
        {!compact && <span>Generate Prompt</span>}
      </button>

      {open && (
        <PlatformPicker
          scene={scene}
          storyboardStyle={storyboardStyle}
          onClose={() => setOpen(false)}
        />
      )}
    </>
  );
}
