"use client";

import { useState, useCallback } from "react";
import { toast } from "sonner";
import type { Platform } from "@/types";
import { PLATFORM_CONFIGS } from "@/types";
import type { GeneratorOutput as GeneratorOutputType } from "@/lib/schemas/universal-prompt.schema";
import GeneratorForm from "./GeneratorForm";
import GeneratorOutputPanel from "./GeneratorOutput";
import GeneratorSkeleton from "./GeneratorSkeleton";

interface GeneratorLayoutProps {
  platform: Platform;
}

export default function GeneratorLayout({ platform }: GeneratorLayoutProps) {
  const [output, setOutput] = useState<GeneratorOutputType | null>(null);
  const [loading, setLoading] = useState(false);
  const [historyId, setHistoryId] = useState<string | null>(null);

  const config = PLATFORM_CONFIGS[platform];

  const handleGenerate = useCallback(async (formData: Record<string, unknown>) => {
    setLoading(true);
    setOutput(null);

    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        // variationCount dihapus (Fix #1) — pakai input.variations.
        // outputFormats dihapus (Fix outputFormats) — server selalu return semua
        // format; tab filtering ditangani di GeneratorOutput.tsx sisi client.
        body: JSON.stringify({
          platform,
          input: { ...formData, platform },
        }),
      });

      const result = await response.json();

      if (!result.success) {
        toast.error(result.error ?? "Gagal generate prompt");
        return;
      }

      setOutput(result.data);
      setHistoryId(result.historyId ?? null);
      toast.success("Prompt berhasil digenerate! 🎉");
    } catch {
      toast.error("Terjadi kesalahan. Coba lagi.");
    } finally {
      setLoading(false);
    }
  }, [platform]);

  return (
    <div className="max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-6 flex items-center gap-3">
        <div
          className="w-12 h-12 rounded-xl flex items-center justify-center text-2xl"
          style={{
            background: `linear-gradient(135deg, ${config.gradientFrom}33, ${config.gradientTo}33)`,
            border: `1px solid ${config.gradientFrom}50`,
          }}
        >
          {config.icon}
        </div>
        <div>
          <div className="flex items-center gap-2">
            <h1 className="text-xl font-bold">{config.name}</h1>
            {config.badge && (
              <span className="text-xs px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-400">
                {config.badge}
              </span>
            )}
          </div>
          <p className="text-sm text-muted-foreground">{config.description}</p>
        </div>
      </div>

      {/* Two-column layout */}
      <div className="grid lg:grid-cols-2 gap-6">
        {/* Left: Form */}
        <div className="space-y-4">
          <GeneratorForm
            platform={platform}
            onGenerate={handleGenerate}
            loading={loading}
          />
        </div>

        {/* Right: Output */}
        <div className="lg:sticky lg:top-6 h-fit">
          {loading ? (
            <GeneratorSkeleton />
          ) : output ? (
            <GeneratorOutputPanel
              output={output}
              platform={platform}
              historyId={historyId}
            />
          ) : (
            <EmptyOutput platform={platform} />
          )}
        </div>
      </div>
    </div>
  );
}

function EmptyOutput({ platform }: { platform: Platform }) {
  const config = PLATFORM_CONFIGS[platform];
  return (
    <div className="rounded-2xl border border-dashed border-border/50 bg-card/30 p-12 text-center">
      <div className="text-5xl mb-4">{config.icon}</div>
      <h3 className="font-semibold text-lg mb-2">Output akan muncul di sini</h3>
      <p className="text-sm text-muted-foreground">
        Isi form di sebelah kiri dan klik <strong>Generate</strong> untuk mulai.
      </p>
      <div className="flex flex-wrap gap-2 justify-center mt-4">
        {config.features.map((f) => (
          <span
            key={f}
            className="text-xs px-2.5 py-1 rounded-full bg-accent text-muted-foreground"
          >
            {f}
          </span>
        ))}
      </div>
    </div>
  );
}
