"use client";

import { useState } from "react";
import { LinkedInPostPreview } from "@/components/generation/linkedin-post-preview";
import { parseCaptionBlocks } from "@/lib/generation/format-caption";
import { cn } from "@/lib/utils";

type PreviewPlatform = "linkedin" | "facebook" | "youtube";

const TABS: { id: PreviewPlatform; label: string }[] = [
  { id: "linkedin", label: "LinkedIn" },
  { id: "facebook", label: "Facebook" },
  { id: "youtube", label: "YouTube" },
];

interface SocialPostPreviewProps {
  caption: string;
  imageUrl?: string | null;
  videoUrl?: string | null;
  videoStatus?: string;
  companyName: string;
  logoDataUrl?: string | null;
  className?: string;
}

function FacebookPostPreview({
  caption,
  imageUrl,
  companyName,
  logoDataUrl,
}: Omit<SocialPostPreviewProps, "videoUrl" | "videoStatus">) {
  const blocks = parseCaptionBlocks(caption);

  return (
    <div className="rounded-xl border border-gray-200 bg-white shadow-sm">
      <div className="flex items-center gap-3 px-4 py-3">
        {logoDataUrl ? (
          <img
            src={logoDataUrl}
            alt=""
            className="h-10 w-10 rounded-full border border-gray-100 object-contain bg-white p-0.5"
          />
        ) : (
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#1877F2] text-xs font-bold text-white">
            {companyName.slice(0, 2).toUpperCase()}
          </div>
        )}
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-gray-900">{companyName}</p>
          <p className="text-xs text-gray-500">Just now · 🌐 Public</p>
        </div>
      </div>

      <div className="space-y-2 px-4 pb-3 text-sm leading-relaxed text-gray-800">
        {blocks.map((block, index) => (
          <p key={index} className="whitespace-pre-wrap">
            {block.lines.join("\n")}
          </p>
        ))}
      </div>

      {imageUrl && (
        <div className="border-t border-gray-100">
          <img src={imageUrl} alt="" className="w-full object-cover" />
        </div>
      )}
    </div>
  );
}

function YouTubePostPreview({
  caption,
  videoUrl,
  videoStatus,
  companyName,
  imageUrl,
}: SocialPostPreviewProps) {
  const hasVideo = Boolean(videoUrl && videoStatus === "generated");
  const title = caption
    .replace(/\*\*/g, "")
    .replace(/#[\w]+/g, "")
    .split(/(?<=[.!?])\s+/)
    .find((s) => s.trim().length > 10)
    ?.trim()
    .slice(0, 80);

  return (
    <div className="rounded-xl border border-gray-200 bg-white shadow-sm overflow-hidden">
      <div className="aspect-video bg-gray-900">
        {hasVideo ? (
          <video
            src={videoUrl!}
            controls
            className="h-full w-full object-contain"
            poster={imageUrl ?? undefined}
          />
        ) : (
          <div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center">
            {imageUrl ? (
              <img src={imageUrl} alt="" className="max-h-32 rounded-md opacity-80" />
            ) : null}
            <p className="text-xs text-gray-400">
              Video generates when VIDEO_PROVIDER=ffmpeg is enabled on the server
            </p>
          </div>
        )}
      </div>
      <div className="px-4 py-3">
        <p className="text-sm font-semibold text-gray-900 line-clamp-2">
          {title || `${companyName} — social update`}
        </p>
        <p className="mt-1 text-xs text-gray-500">{companyName}</p>
        <p className="mt-2 max-h-24 overflow-hidden text-xs leading-relaxed text-gray-600 whitespace-pre-wrap">
          {caption.slice(0, 400)}
          {caption.length > 400 ? "…" : ""}
        </p>
      </div>
    </div>
  );
}

export function SocialPostPreview(props: SocialPostPreviewProps) {
  const [active, setActive] = useState<PreviewPlatform>("linkedin");
  const showYouTube = Boolean(props.videoUrl && props.videoStatus === "generated");

  return (
    <div className={cn("space-y-3", props.className)}>
      <div className="flex flex-wrap items-center gap-2">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActive(tab.id)}
            className={cn(
              "rounded-full px-3 py-1 text-xs font-medium transition-colors",
              active === tab.id
                ? "bg-brand-600 text-white"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200",
            )}
          >
            {tab.label}
            {tab.id === "youtube" && !showYouTube && (
              <span className="ml-1 opacity-70">(no video yet)</span>
            )}
          </button>
        ))}
      </div>

      <p className="text-xs text-gray-500">
        Same caption and image publish to LinkedIn and Facebook
        {showYouTube ? "; MP4 uploads to YouTube when connected." : "."}
      </p>

      {active === "linkedin" && (
        <LinkedInPostPreview
          caption={props.caption}
          imageUrl={props.imageUrl}
          companyName={props.companyName}
          logoDataUrl={props.logoDataUrl}
        />
      )}
      {active === "facebook" && (
        <FacebookPostPreview
          caption={props.caption}
          imageUrl={props.imageUrl}
          companyName={props.companyName}
          logoDataUrl={props.logoDataUrl}
        />
      )}
      {active === "youtube" && (
        <YouTubePostPreview {...props} />
      )}
    </div>
  );
}
