"use client";



import { Check, Loader2, Plus } from "lucide-react";

import { useCallback, useEffect, useMemo, useState } from "react";

import { DashboardLayout } from "@/components/layout/dashboard-layout";

import { OnboardingFooter } from "@/components/layout/onboarding-footer";

import { PageHeader } from "@/components/layout/page-header";

import { Button } from "@/components/ui/button";

import { Card } from "@/components/ui/card";

import { SocialPostPreview } from "@/components/generation/social-post-preview";

import { QuickPublishPanel } from "@/components/publishing/quick-publish-panel";

import { cn } from "@/lib/utils";

import { getPostDisplayLabel } from "@/lib/context/format-sequence-context";

import { describeScheduleStatus } from "@/lib/scheduling/display";
import { ScheduleReadinessBanner } from "@/components/scheduling/schedule-readiness-banner";
import { AutoPostMonitor } from "@/components/scheduling/auto-post-monitor";
import { AutoPostMonitorSafe } from "@/components/scheduling/auto-post-monitor-safe";
import { flushProjectsSync } from "@/lib/client/projects-sync";
import { hasUsablePostingContext } from "@/lib/scheduling/setup-ready";
import { fetchAIConfig, fetchGeneratedPosts, generatePost } from "@/lib/client/generation-api";
import { getGenerationPayload } from "@/lib/client/generation-payload";
import type { GeneratedPost } from "@/types/workflow";
import { useContextStore } from "@/store/context-store";
import { selectActiveProject } from "@/hooks/use-projects-hydrated";
import { useProjectsStore } from "@/store/projects-store";



const STEPS = [
  "Generate post from context",
  "Generate image (OpenAI or branded template)",
  "Publish to LinkedIn, Facebook & YouTube (when video ready)",
] as const;



export default function LiveGenerationPage() {

  const activeProject = useProjectsStore(selectActiveProject);

  const context = useContextStore((s) => s.context);
  const saveContext = useContextStore((s) => s.saveContext);

  const brand = useProjectsStore((s) => s.getActiveData()?.brand);

  const accounts = useProjectsStore((s) => s.getActiveData()?.accounts ?? []);

  const schedule = useProjectsStore((s) => s.getActiveData()?.schedule);

  const scheduleLabel = useMemo(() => {
    if (!activeProject?.id) return "Schedule not set";
    try {
      return describeScheduleStatus({
        projectId: activeProject.id,
        timezone: activeProject.timezone ?? "UTC",
        postsPerDay: schedule?.postsPerDay ?? 2,
        scheduleSeed: schedule?.scheduleSeed,
      });
    } catch {
      return "Schedule not set";
    }
  }, [activeProject?.id, activeProject?.timezone, schedule?.postsPerDay, schedule?.scheduleSeed]);



  const [latest, setLatest] = useState<GeneratedPost | null>(null);

  const [aiConfig, setAiConfig] = useState<string>("");

  const [generating, setGenerating] = useState(false);

  const [error, setError] = useState("");

  const [step, setStep] = useState(0);



  const loadLatest = useCallback(async () => {

    if (!activeProject?.id) return;

    const posts = await fetchGeneratedPosts(activeProject.id, activeProject.name);

    const post = posts[0] ?? null;

    setLatest(post);

    if (post?.status === "published") setStep(3);
    else if (post?.imageUrl) setStep(2);
    else if (post) setStep(1);

  }, [activeProject?.id, activeProject?.name]);



  useEffect(() => {

    void fetchAIConfig().then((c) =>

      setAiConfig(`${c.provider} / ${c.model} · images: ${c.imageProvider}`),

    );

    void loadLatest();

  }, [loadLatest]);



  const handleGenerate = async () => {
    if (!activeProject?.id) {
      setError("Select or create a project first.");
      return;
    }

    if (activeProject.status === "paused") {
      setError("Project is paused. Activate it in My Project.");
      return;
    }

    if (!hasUsablePostingContext(context)) {
      setError("Open Posting Context, add sequence content, then click Save Context.");
      return;
    }

    setGenerating(true);
    setError("");
    setStep(1);

    try {
      // Persist context + schedule so Generate Now works even if user skipped Save clicks.
      const store = useProjectsStore.getState();
      saveContext();
      if (!store.getActiveData()?.schedule?.saved) {
        store.saveActiveSchedule();
      }
      try {
        await flushProjectsSync();
      } catch (syncErr) {
        console.error("Pre-generate project sync failed:", syncErr);
      }

      const payload = getGenerationPayload(
        (Array.isArray(context.posts) ? context.posts[0]?.id : undefined) ?? "",
        "next",
      );

      if (!payload) {
        setError("Complete project setup before generating.");
        setStep(0);
        return;
      }

      const post = await generatePost(payload);
      setLatest(post);
      setStep(post.imageUrl ? 2 : 1);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Generation failed");
      setStep(0);
    } finally {
      setGenerating(false);
    }
  };



  const handleQuickPublished = (post: GeneratedPost) => {

    setLatest(post);

    if (post.status === "published") setStep(3);

  };



  return (

    <DashboardLayout>

      <PageHeader

        title="Live Generation"

        subtitle="Generate once, or enable Loop Post Sequence — cron publishes drafts directly (no approve step)"

      />

      <div className="relative flex-1 px-8 pb-24 pt-2">

        {aiConfig && (

          <p className="mb-4 text-xs text-gray-400">Provider: {aiConfig}</p>

        )}



        {latest?.imageWarning && (

          <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">

            Image: {latest.imageWarning}

            {latest.imageProvider && (

              <span className="mt-1 block text-xs text-amber-700">

                Rendered with: {latest.imageProvider}

                {latest.imageProviderChain && (
                  <span className="block">Chain: {latest.imageProviderChain}</span>
                )}

              </span>

            )}

          </div>

        )}



        {(latest?.imageProvider === "openai" || latest?.imageProvider === "gemini") &&
          !latest.imageWarning && (
          <p className="mb-4 text-xs text-green-600">
            Image: {latest.imageProvider === "gemini" ? "Google Gemini" : "OpenAI DALL-E"} (
            {latest.imageProvider}
            {latest.imageProviderChain ? ` · ${latest.imageProviderChain}` : ""})
          </p>
        )}



        {latest?.imageProvider === "placeholder" && (
          <p className="mb-4 text-xs text-gray-600">
            Image: story-aligned branded card (Problem / Impact from your context)
            {latest.imageProviderChain ? ` · ${latest.imageProviderChain}` : ""}
          </p>
        )}



        {error && (

          <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">

            {error}

          </div>

        )}



        <ScheduleReadinessBanner projectId={activeProject?.id} />

        <AutoPostMonitorSafe>
          <AutoPostMonitor projectId={activeProject?.id} />
        </AutoPostMonitorSafe>

        <div className="grid gap-6 lg:grid-cols-2">

          <Card>

            <div className="space-y-5">

              <div className="inline-flex items-center gap-2 rounded-full bg-green-50 px-3 py-1 text-sm font-medium text-green-700">

                <span className="h-2 w-2 rounded-full bg-green-500" />

                {scheduleLabel}

              </div>

              <p className="text-sm text-gray-600">

                Now generating:{" "}

                <span className="font-semibold text-gray-900">

                  {latest?.title ??
                    (Array.isArray(context.posts) && context.posts[0]
                      ? getPostDisplayLabel(context.posts[0], 0)
                      : "Next in sequence")}

                </span>

              </p>



              <ul className="space-y-3">

                {STEPS.map((label, index) => (

                  <li key={label} className="flex items-center gap-3 text-sm text-gray-700">

                    <span

                      className={cn(

                        "flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2",

                        step > index

                          ? "border-green-500 bg-green-500 text-white"

                          : "border-gray-300 bg-white",

                      )}

                    >

                      {step > index && <Check className="h-3 w-3" />}

                    </span>

                    {label}

                  </li>

                ))}

              </ul>



              <div className="flex flex-wrap justify-end gap-2 pt-4">

                {latest && latest.status !== "published" && latest.status !== "rejected" && (

                  <p className="self-center text-xs font-medium text-emerald-700">

                    Queued for auto-publish at next morning/evening slot — no approval needed

                  </p>

                )}

                <Button

                  type="button"

                  variant="purple"

                  size="sm"

                  disabled={generating || activeProject?.status === "paused"}

                  onClick={() => void handleGenerate()}

                >

                  {generating ? (

                    <Loader2 className="h-4 w-4 animate-spin" />

                  ) : (

                    <Plus className="h-4 w-4" />

                  )}

                  Generate Now

                </Button>

              </div>

            </div>

          </Card>



          <Card title="Live Preview — LinkedIn · Facebook · YouTube">

            {latest ? (

              <div className="space-y-4">

                <SocialPostPreview

                  caption={latest.caption}

                  imageUrl={latest.imageUrl}

                  videoUrl={latest.videoUrl}

                  videoStatus={latest.videoStatus}

                  companyName={brand?.companyName || activeProject?.name || "Company"}

                  logoDataUrl={brand?.logoDataUrl}

                />

                <p className="text-xs text-gray-500">

                  Engagement score:{" "}

                  {latest.engagementScore !== null ? (

                    <span className="font-semibold text-green-600">

                      {latest.engagementScore} Excellent

                    </span>

                  ) : (

                    "—"

                  )}

                </p>

              </div>

            ) : (

              <div className="flex min-h-[280px] flex-col items-center justify-center text-center">

                <p className="text-sm text-gray-400">Waiting for generation...</p>

                <p className="mt-8 self-start text-xs text-gray-400">Engagement score: —</p>

              </div>

            )}

          </Card>

        </div>



        {latest && activeProject && (

          <QuickPublishPanel

            className="mt-6"

            post={latest}

            accounts={accounts}

            projectStatus={activeProject.status}

            onPublished={handleQuickPublished}

          />

        )}

      </div>

      <OnboardingFooter currentStep={7} />

    </DashboardLayout>

  );

}


