"use client";

import { Loader2, Upload } from "lucide-react";
import { useCallback, useState } from "react";
import { DashboardLayout } from "@/components/layout/dashboard-layout";
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 { selectActiveAccounts } from "@/store/project-selectors";
import { useProjectsStore } from "@/store/projects-store";
import { listVisiblePlatforms } from "@/lib/social/platforms";

export default function ContentLibraryPage() {
  const activeProject = useProjectsStore(selectActiveProject);
  const accounts = useProjectsStore(selectActiveAccounts);

  const [title, setTitle] = useState("");
  const [caption, setCaption] = useState("");
  const [hashtags, setHashtags] = useState("");
  const [linkUrl, setLinkUrl] = useState("");
  const [cta, setCta] = useState("");
  const [platforms, setPlatforms] = useState<string[]>(["linkedin"]);
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const [mediaType, setMediaType] = useState<"content" | "image" | "video">("content");
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [importing, setImporting] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const connectedPlatforms = listVisiblePlatforms()
    .map((p) => p.id)
    .filter((id) => accounts.find((a) => a.platform === id)?.connected);

  const togglePlatform = (id: string) => {
    setPlatforms((prev) =>
      prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id],
    );
  };

  const handleUpload = async (file: File, kind: "image" | "video") => {
    setUploading(true);
    setError("");
    try {
      const form = new FormData();
      form.append("file", file);
      const res = await fetch("/api/content/upload", { method: "POST", body: form });
      const data = (await res.json()) as { url?: string; error?: string };
      if (!res.ok) throw new Error(data.error || "Upload failed");
      if (kind === "image") {
        setImageUrl(data.url ?? null);
        setMediaType("image");
      } else {
        setVideoUrl(data.url ?? null);
        setMediaType("video");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Upload failed");
    } finally {
      setUploading(false);
    }
  };

  const handleSaveManual = async () => {
    if (!activeProject?.id) {
      setError("Select or create a project first.");
      return;
    }
    if (!caption.trim()) {
      setError("Caption is required.");
      return;
    }
    setSaving(true);
    setError("");
    setMessage("");
    try {
      const res = await fetch("/api/content/manual", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectId: activeProject.id,
          title,
          caption,
          hashtags,
          linkUrl,
          cta,
          mediaType,
          platforms: platforms.length ? platforms : connectedPlatforms.slice(0, 1),
          imageUrl,
          videoUrl,
        }),
      });
      const data = (await res.json()) as { error?: string; post?: { id: string } };
      if (!res.ok) throw new Error(data.error || "Save failed");
      setMessage(`Draft saved. Review it in Post Review.`);
      setCaption("");
      setTitle("");
      setHashtags("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const handleCsvImport = useCallback(
    async (file: File) => {
      if (!activeProject?.id) {
        setError("Select or create a project first.");
        return;
      }
      setImporting(true);
      setError("");
      setMessage("");
      try {
        const form = new FormData();
        form.append("file", file);
        form.append("projectId", activeProject.id);
        const res = await fetch("/api/content/import/csv", { method: "POST", body: form });
        const data = (await res.json()) as {
          error?: string;
          imported?: number;
          errors?: { row: number; message: string }[];
        };
        if (!res.ok) throw new Error(data.error || "Import failed");
        const errCount = data.errors?.length ?? 0;
        setMessage(
          `Imported ${data.imported ?? 0} draft(s)${errCount ? ` · ${errCount} row error(s)` : ""}.`,
        );
      } catch (err) {
        setError(err instanceof Error ? err.message : "Import failed");
      } finally {
        setImporting(false);
      }
    },
    [activeProject?.id],
  );

  return (
    <DashboardLayout>
      <PageHeader
        title="Content Library"
        subtitle="Create manual posts or bulk-import CSV — all content uses the same review, schedule, and publish pipeline. AI-generated content also receives AI-specific generation QA."
      />
      <div className="flex-1 space-y-6 px-4 pb-24 pt-2 sm:px-6 lg:px-8">
        <InfoBanner>
          Content uses your project brand and context only — no predefined demo businesses.
          Manual and AI posts share Post Review, scheduling, and publishing.
        </InfoBanner>

        {error && <p className="text-sm font-medium text-red-600">{error}</p>}
        {message && <p className="text-sm font-medium text-green-700">{message}</p>}

        <div className="grid gap-6 lg:grid-cols-[1.4fr_1fr]">
          <Card title="Manual compose">
            <div className="space-y-4">
              <Input
                label="Title (optional)"
                id="manual-title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Post title"
              />
              <Textarea
                label="Caption"
                id="manual-caption"
                value={caption}
                onChange={(e) => setCaption(e.target.value)}
                placeholder="Write your caption…"
                rows={6}
              />
              <Input
                label="Hashtags"
                id="manual-hashtags"
                value={hashtags}
                onChange={(e) => setHashtags(e.target.value)}
                placeholder="Launch Product Brand (space or semicolon separated)"
              />
              <div className="grid gap-4 sm:grid-cols-2">
                <Input
                  label="Link URL"
                  id="manual-link"
                  value={linkUrl}
                  onChange={(e) => setLinkUrl(e.target.value)}
                  placeholder="https://"
                />
                <Input
                  label="CTA"
                  id="manual-cta"
                  value={cta}
                  onChange={(e) => setCta(e.target.value)}
                  placeholder="Learn more"
                />
              </div>

              <div>
                <p className="mb-2 text-sm font-medium text-gray-700">Platforms</p>
                <div className="flex flex-wrap gap-2">
                  {listVisiblePlatforms().map((p) => (
                    <button
                      key={p.id}
                      type="button"
                      onClick={() => togglePlatform(p.id)}
                      className={`rounded-lg border px-3 py-1.5 text-sm ${
                        platforms.includes(p.id)
                          ? "border-brand-600 bg-brand-50 text-brand-800"
                          : "border-gray-200 text-gray-600"
                      }`}
                    >
                      {p.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="flex flex-wrap gap-3">
                <label className="cursor-pointer">
                  <input
                    type="file"
                    accept="image/png,image/jpeg,image/webp"
                    className="hidden"
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (f) void handleUpload(f, "image");
                    }}
                  />
                  <span className="inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm hover:bg-gray-50">
                    <Upload className="h-4 w-4" />
                    {uploading ? "Uploading…" : "Upload image"}
                  </span>
                </label>
                <label className="cursor-pointer">
                  <input
                    type="file"
                    accept="video/mp4"
                    className="hidden"
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (f) void handleUpload(f, "video");
                    }}
                  />
                  <span className="inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm hover:bg-gray-50">
                    <Upload className="h-4 w-4" />
                    Upload video
                  </span>
                </label>
              </div>
              {(imageUrl || videoUrl) && (
                <p className="text-xs text-gray-500">
                  Media: {imageUrl && `image ${imageUrl}`}
                  {videoUrl && ` video ${videoUrl}`}
                </p>
              )}

              <div className="flex justify-end gap-2 pt-2">
                <Button type="button" onClick={() => void handleSaveManual()} disabled={saving}>
                  {saving ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Saving…
                    </>
                  ) : (
                    "Save draft"
                  )}
                </Button>
              </div>
            </div>
          </Card>

          <Card title="CSV import">
            <p className="mb-4 text-sm text-gray-600">
              Bulk import up to 200 rows. All imports are saved as drafts for review.
            </p>
            <a
              href="/api/content/import/template"
              className="text-sm font-medium text-brand-600 hover:underline"
            >
              Download CSV template
            </a>
            <div className="mt-4">
              <label className="cursor-pointer">
                <input
                  type="file"
                  accept=".csv,text/csv"
                  className="hidden"
                  onChange={(e) => {
                    const f = e.target.files?.[0];
                    if (f) void handleCsvImport(f);
                  }}
                />
                <span className="inline-flex w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-gray-200 px-4 py-8 text-sm text-gray-600 hover:border-brand-300 hover:bg-brand-50/30">
                  {importing ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" /> Importing…
                    </>
                  ) : (
                    <>
                      <Upload className="h-4 w-4" /> Choose CSV file
                    </>
                  )}
                </span>
              </label>
            </div>
          </Card>
        </div>
      </div>
    </DashboardLayout>
  );
}
