"use client";

import { Loader2, Plus, RefreshCw, Sparkles } from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, 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 { InfoBanner } from "@/components/ui/info-banner";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { selectActiveProject } from "@/hooks/use-projects-hydrated";
import { flushProjectsSync } from "@/lib/client/projects-sync";
import { generatePost } from "@/lib/client/generation-api";
import { getGenerationPayload } from "@/lib/client/generation-payload";
import { hasUsablePostingContext } from "@/lib/scheduling/setup-ready";
import {
  buildBrandContextPreview,
  MAX_SEQUENCE_POSTS,
} from "@/lib/context/sequence-templates";
import { cn } from "@/lib/utils";
import { useBrandStore } from "@/store/brand-store";
import { useContextStore } from "@/store/context-store";
import { useProjectsStore } from "@/store/projects-store";

export default function PostingContextPage() {
  const router = useRouter();
  const activeProject = useProjectsStore(selectActiveProject);
  const { brand } = useBrandStore();
  const {
    context,
    selectedPostId,
    setContextName,
    selectPost,
    addPost,
    updatePost,
    setPosts,
    saveContext,
  } = useContextStore();

  const [generatingId, setGeneratingId] = useState<string | null>(null);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [syncing, setSyncing] = useState(false);

  const selectedPost = context.posts.find((p) => p.id === selectedPostId) ?? null;
  const isPaused = activeProject?.status === "paused";

  const applyBrandPreview = useCallback(
    (postId: string) => {
      if (!activeProject) return;
      const index = context.posts.findIndex((p) => p.id === postId);
      if (index < 0) return;
      const preview = buildBrandContextPreview(index, brand, activeProject, context.name);
      updatePost(postId, { content: preview });
    },
    [activeProject, brand, context.name, context.posts, updatePost],
  );

  const handleSelectPost = (postId: string) => {
    selectPost(postId);
    applyBrandPreview(postId);
    setError("");
  };

  const handleRefreshAllFromBrand = async () => {
    if (!activeProject?.id) return;
    setError("");
    setMessage("Refreshing from website and brand profile…");
    try {
      const res = await fetch("/api/context/refresh-previews", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectId: activeProject.id,
          project: activeProject,
          brand,
          posts: context.posts,
          campaignName: context.name,
        }),
      });
      const data = (await res.json()) as { posts?: typeof context.posts; error?: string };
      if (!res.ok) throw new Error(data.error || "Refresh failed");
      if (data.posts) setPosts(data.posts);
      setMessage("All context previews refreshed from website + brand profile.");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Refresh failed");
      setMessage("");
    }
  };

  const handleSave = () => {
    saveContext();
    setError("");
    setMessage("Saving posting context to server…");
    setSyncing(true);
    void flushProjectsSync()
      .then(() => {
        setSyncing(false);
        setMessage("Posting context saved. AI will use the preview text only. Post sequence is ready.");
      })
      .catch((err) => {
        setSyncing(false);
        setError(err instanceof Error ? err.message : "Server sync failed");
        setMessage("");
      });
  };

  const handleGenerate = async (sequencePostId: string) => {
    if (isPaused) {
      setError("Project is paused. Activate it in My Project to generate content.");
      return;
    }
    if (!activeProject?.id) {
      setError("Select or create a project first.");
      return;
    }
    if (!activeProject.name.trim()) {
      setError("Complete My Project (Step 1) before generating posts.");
      return;
    }
    if (!hasUsablePostingContext(context)) {
      setError("Add sequence content, then click Save Context before generating.");
      return;
    }

    const postItem = context.posts.find((p) => p.id === sequencePostId);
    if (!postItem?.content.trim()) {
      setError("Context preview is empty. Select a post to auto-generate from brand.");
      return;
    }

    setGeneratingId(sequencePostId);
    setError("");
    setMessage("");

    try {
      saveContext();
      try {
        await flushProjectsSync();
      } catch (syncErr) {
        console.error("Pre-generate context sync failed:", syncErr);
      }
      const payload = getGenerationPayload(sequencePostId, "specific");
      if (!payload) {
        setError("Complete project setup before generating.");
        return;
      }
      const post = await generatePost(payload);
      setMessage(`Generated "${post.title}" — review it in Post Review.`);
      router.push(`/generated-posts?highlight=${post.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Generation failed");
    } finally {
      setGeneratingId(null);
    }
  };

  return (
    <DashboardLayout>
      <PageHeader
        title="Posting Context"
        subtitle="Define your rotating B2B post sequence (Problem → Impact → hashtags per post)."
      />
      <div className="w-full min-w-0 flex-1 px-4 pb-32 pt-2 sm:px-6 lg:px-8">
        {isPaused && (
          <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
            Project is <strong>Paused</strong> — generation and publishing are disabled.
          </div>
        )}

        <div className="mx-auto grid w-full max-w-7xl grid-cols-1 gap-4 lg:grid-cols-2 lg:items-start lg:gap-6">
          <Card className="min-w-0 p-4 sm:p-6">
            <div className="space-y-5">
              <Input
                label="Context Name"
                id="context-name"
                value={context.name}
                onChange={(e) => setContextName(e.target.value)}
              />
              <InfoBanner>
                Each post uses compact <strong>Problem → Impact → Hashtags</strong> context
                (story arc drives topic order). Click <strong>Refresh all from brand</strong>{" "}
                to rebuild from your project + brand profile, then <strong>Save Context</strong>.
              </InfoBanner>

              <div>
                <h3 className="mb-3 text-sm font-semibold text-gray-900">Post Sequence</h3>
                <div className="space-y-2 sm:space-y-3">
                  {context.posts.map((post, index) => {
                    const selected = selectedPostId === post.id;
                    return (
                      <button
                        key={post.id}
                        type="button"
                        onClick={() => handleSelectPost(post.id)}
                        className={cn(
                          "w-full min-w-0 rounded-lg border bg-white p-3 text-left transition-colors sm:p-4",
                          selected
                            ? "border-brand-600 ring-1 ring-brand-600/20"
                            : "border-gray-200 hover:border-gray-300",
                        )}
                      >
                        <div className="flex min-w-0 gap-3">
                          <span
                            className={cn(
                              "flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold",
                              selected
                                ? "bg-brand-600 text-white"
                                : "bg-info-bg text-action",
                            )}
                          >
                            {index + 1}
                          </span>
                          <div className="min-w-0 flex-1 overflow-hidden">
                            <p className="truncate text-sm font-semibold text-gray-900">
                              {post.title || `Post ${index + 1}`}
                            </p>
                            {post.summary && (
                              <p className="mt-1 line-clamp-2 text-xs text-gray-500">
                                {post.summary}
                              </p>
                            )}
                            {post.tag && (
                              <p className="mt-2 text-xs font-medium text-brand-600">
                                Tag: {post.tag}
                              </p>
                            )}
                          </div>
                        </div>
                      </button>
                    );
                  })}
                </div>
                <p className="mt-3 text-xs text-gray-400">
                  ↻ loops continuously through this sequence (Post 1 → Post 2 → … → Post 5 → Post 1)
                </p>
              </div>

              <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="w-full sm:w-auto"
                  onClick={addPost}
                  disabled={context.posts.length >= MAX_SEQUENCE_POSTS}
                >
                  <Plus className="h-4 w-4" />
                  {context.posts.length >= MAX_SEQUENCE_POSTS ? "Max 5 posts" : "Add Post"}
                </Button>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="w-full sm:w-auto"
                  onClick={handleRefreshAllFromBrand}
                  disabled={!activeProject}
                >
                  <RefreshCw className="h-4 w-4" />
                  Refresh all from brand
                </Button>
                <Button
                  type="button"
                  className="w-full sm:w-auto"
                  onClick={handleSave}
                  disabled={syncing}
                >
                  {syncing ? "Saving…" : "Save Context"}
                </Button>
              </div>
            </div>
          </Card>

          <Card className="flex min-h-0 min-w-0 flex-col p-4 sm:p-6">
            {selectedPost ? (
              <div className="flex min-h-0 flex-1 flex-col gap-4">
                <div className="rounded-lg border border-gray-100 bg-gray-50 px-3 py-2 text-xs text-gray-600">
                  <p className="font-semibold text-gray-800">{selectedPost.title}</p>
                  {selectedPost.summary && <p className="mt-1">{selectedPost.summary}</p>}
                  {selectedPost.tag && (
                    <p className="mt-1 font-medium text-brand-600">Tag: {selectedPost.tag}</p>
                  )}
                </div>

                <Textarea
                  label="Context preview (edit here — sent to AI as-is)"
                  id="context-preview"
                  rows={16}
                  className="min-h-[280px] w-full flex-1 resize-y font-mono text-[13px] leading-relaxed sm:min-h-[360px] lg:min-h-[420px]"
                  value={selectedPost.content}
                  onChange={(e) =>
                    updatePost(selectedPost.id, { content: e.target.value })
                  }
                  placeholder={`Problem: Scaling ad spend no longer produces proportional returns. Doubling the budget doesn't double the pipeline.

Impact: False growth signals — higher spend can look like momentum while actual ROI quietly declines.

#MarketingROI #BusinessGrowth #LeadGeneration #Scaling`}
                />

                <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="w-full sm:w-auto"
                    disabled={!activeProject}
                    onClick={() => applyBrandPreview(selectedPost.id)}
                  >
                    <RefreshCw className="h-4 w-4" />
                    Regenerate from brand
                  </Button>
                  <Button
                    type="button"
                    variant="purple"
                    className="w-full sm:w-auto"
                    disabled={isPaused || generatingId !== null}
                    onClick={() => void handleGenerate(selectedPost.id)}
                  >
                    {generatingId === selectedPost.id ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin" />
                        Generating…
                      </>
                    ) : (
                      <>
                        <Sparkles className="h-4 w-4" />
                        Generate from context
                      </>
                    )}
                  </Button>
                </div>
              </div>
            ) : (
              <p className="text-sm text-gray-500">Select a post from the sequence to edit.</p>
            )}

            {error && <p className="mt-4 text-sm font-medium text-red-600">{error}</p>}
            {message && <p className="mt-4 text-sm font-medium text-green-700">{message}</p>}
          </Card>
        </div>
      </div>
      <OnboardingFooter
        currentStep={3}
        nextDisabled={!context.saved}
        onBeforeNext={() => {
          if (!context.saved) {
            setError("Save Context before continuing to the next step.");
            return false;
          }
          return true;
        }}
      />
    </DashboardLayout>
  );
}
