"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, usePathname } from "next/navigation";
import { PenSquare, Trash2, ArrowUp, ArrowDown, PenLine, Globe } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { RegionBadge } from "@/components/composer/RegionSelector";
import type { ContentTrack, Region } from "@/lib/types";
import { TRACK_LABELS, TRACK_ORDER } from "@/lib/track-display";

const TRACK_COLORS: Record<string, string> = {
  ENTERPRISE: "bg-blue-500",
  PRODUCT: "bg-indigo-500",
  DEVELOPER: "bg-purple-500",
  THOUGHT_LEADERSHIP: "bg-emerald-500",
  EVENT: "bg-orange-500",
  TI_CULTURAL: "bg-pink-500",
};

// R6: Content mix ratio — 80% value / 20% promotional (industry best practice)
const VALUE_TRACKS: ContentTrack[] = ["DEVELOPER", "THOUGHT_LEADERSHIP", "TI_CULTURAL"];
const PROMO_TRACKS: ContentTrack[] = ["PRODUCT", "ENTERPRISE", "EVENT"];

const ALL_TRACKS: ContentTrack[] = [...TRACK_ORDER] as ContentTrack[];

interface PostAccountStatus {
  socialAccount: { id: string; network: string; accountName: string };
  publishStatus: string;
  staggeredPublishAt: string | null;
}

interface QueuePost {
  id: string;
  content: string;
  status: string;
  scheduledAt: string | null;
  originalScheduledAt: string | null;
  queuePosition: number | null;
  publishPriority: string;
  author: { id: string; name: string | null; email: string };
  postAccounts?: PostAccountStatus[];
  region?: Region | null;
  createdAt: string;
}

interface TrackData {
  config: {
    weeklySlotCap: number;
    requiresApproval: boolean;
  } | null;
  slotsUsed: number;
  posts: QueuePost[];
}

export default function QueuePage() {
  const router = useRouter();
  const pathname = usePathname();
  const [queueData, setQueueData] = useState<Record<string, TrackData>>({});
  const [loading, setLoading] = useState(true);
  const [regionFilter, setRegionFilter] = useState<Region | "all">("all");
  const [filterRegions, setFilterRegions] = useState<string[]>([]);

  useEffect(() => {
    fetch("/api/v1/posts/filters")
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data && Array.isArray(data.regions)) setFilterRegions(data.regions);
      })
      .catch(() => {});
  }, []);

  const refreshQueue = useCallback(async () => {
    const params = regionFilter !== "all" ? `?region=${regionFilter}` : "";
    const qRes = await fetch(`/api/v1/queue${params}`, { cache: "no-store" });
    if (qRes.ok) {
      const data = await qRes.json();
      setQueueData(data.tracks);
    }
  }, [regionFilter]);

  // UXG-12+13 fix: Refetch on every navigation to this page (pathname change triggers re-run)
  useEffect(() => {
    // Intentional: entering this page should immediately show a loading state
    // before the refetch resolves on navigation/filter changes.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setLoading(true);
    const params = regionFilter !== "all" ? `?region=${regionFilter}` : "";
    fetch(`/api/v1/queue${params}`, { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : { tracks: {} }))
      .then((data: { tracks: Record<string, TrackData> }) => setQueueData(data.tracks))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [pathname, regionFilter]);

  const handleDelete = async (postId: string) => {
    if (!confirm("Delete this post?")) return;
    const res = await fetch(`/api/v1/posts/${postId}`, { method: "DELETE" });
    if (res.ok) refreshQueue();
  };

  const [reorderError, setReorderError] = useState("");

  const handleReorder = async (postId: string, currentPosition: number, direction: "up" | "down") => {
    const newPosition = direction === "up" ? currentPosition - 1 : currentPosition + 1;
    if (newPosition < 1) return;
    setReorderError("");
    const res = await fetch("/api/v1/queue/reorder", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ postId, newPosition }),
    });
    if (res.ok) {
      refreshQueue();
    } else {
      const data = await res.json().catch(() => ({ error: "Reorder failed" }));
      setReorderError(data.error ?? `Reorder failed (${res.status})`);
    }
  };

  const handleApprove = async (postId: string) => {
    const res = await fetch(`/api/v1/posts/${postId}/review`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action: "approve" }),
    });
    if (res.ok) refreshQueue();
  };

  return (
    <div className="space-y-6">
      <div className="border-b border-gray-100 -mx-4 md:-mx-6 -mt-4 md:-mt-6 px-4 sm:px-8 py-4 sm:py-5 mb-4 sm:mb-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-semibold text-gray-900">Publishing Queue</h1>
            <p className="text-sm text-gray-500">Manage content across all tracks</p>
          </div>
          <div className="flex items-center gap-2 w-full sm:w-auto">
            <Select value={regionFilter} onValueChange={(v) => setRegionFilter((v ?? "all") as Region | "all")}>
              <SelectTrigger className="w-[130px] sm:w-[160px] h-8 text-xs border-gray-200" data-testid="queue-region-filter">
                <Globe className="h-3 w-3 mr-1 text-gray-500" />
                <SelectValue placeholder="All Regions" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Regions</SelectItem>
                {filterRegions.map((r) => (
                  <SelectItem key={r} value={r}>{r === "GLOBAL" ? "Global" : r}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button
              onClick={() => router.push("/dashboard/compose?priority=EMERGENCY")}
              className="bg-red-600 hover:bg-red-700 text-white text-sm flex-1 sm:flex-none"
            >
              Emergency Post
            </Button>
          </div>
        </div>
      </div>

      {reorderError && (
        <div className="rounded-lg bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700">
          {reorderError}
        </div>
      )}

      {/* R6: Content mix ratio guidance */}
      {!loading && (() => {
        const valueCount = VALUE_TRACKS.reduce((sum, t) => sum + (queueData[t]?.slotsUsed ?? 0), 0);
        const promoCount = PROMO_TRACKS.reduce((sum, t) => sum + (queueData[t]?.slotsUsed ?? 0), 0);
        const total = valueCount + promoCount;
        const valuePct = total > 0 ? Math.round((valueCount / total) * 100) : 0;
        const promoPct = total > 0 ? 100 - valuePct : 0;
        const isHealthy = total === 0 || valuePct >= 70;

        return total > 0 ? (
          <div className={`flex items-center gap-3 p-3 rounded-lg text-sm ${isHealthy ? "bg-green-50 border border-green-200" : "bg-amber-50 border border-amber-200"}`}>
            <span className="font-medium text-gray-700">Content Mix:</span>
            <div className="flex-1 h-2 rounded-full bg-gray-200 overflow-hidden max-w-xs">
              <div className="h-full bg-green-500 rounded-full" style={{ width: `${valuePct}%` }} />
            </div>
            <span className={`text-xs font-medium ${isHealthy ? "text-green-700" : "text-amber-700"}`}>
              {valuePct}% value / {promoPct}% promo
            </span>
            <span className="text-xs text-gray-400">(target: 80/20)</span>
          </div>
        ) : null;
      })()}


      {loading ? (
        <div className="flex gap-4 overflow-x-hidden pb-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="min-w-[280px] w-[280px] space-y-3">
              <div className="h-5 w-24 rounded bg-gray-100 animate-pulse" />
              <div className="h-24 rounded-lg bg-gray-50 border border-gray-100 animate-pulse" />
              <div className="h-20 rounded-lg bg-gray-50 border border-gray-100 animate-pulse" />
            </div>
          ))}
        </div>
      ) : (
        <div className="flex gap-4 overflow-x-auto pb-4 snap-x snap-mandatory">
          {ALL_TRACKS.map((track) => {

            const data = queueData[track];
            const cap = data?.config?.weeklySlotCap ?? 0;
            const used = data?.slotsUsed ?? 0;

            // FIX: Sort posts soonest-first so the immediate next post is at the top
            const sortedPosts = data?.posts ? [...data.posts].sort((a, b) => {
              const timeA = a.scheduledAt ? new Date(a.scheduledAt).getTime() : Infinity;
              const timeB = b.scheduledAt ? new Date(b.scheduledAt).getTime() : Infinity;
              return timeA - timeB;
            }) : [];

            return (
              <div key={track} className="space-y-3 min-w-[280px] w-[280px] shrink-0 snap-start">
                {/* Column header with capacity bar */}
                <div className="space-y-1.5">
                  <div className="flex items-center gap-2">
                    <div className={`h-3 w-3 rounded-full ${TRACK_COLORS[track]}`} />
                    <span className="text-sm font-semibold text-gray-900">
                      {TRACK_LABELS[track]}
                    </span>
                    <span className={`text-xs ml-auto font-medium ${cap > 0 && used >= cap ? "text-red-600" : "text-gray-500"}`}>
                      {used}/{cap > 0 ? cap : "\u221E"} slots
                    </span>
                  </div>
                  {cap > 0 && (
                    <div className="h-1.5 w-full rounded-full bg-gray-100 overflow-hidden">
                      <div
                        className={`h-full rounded-full transition-all ${
                          used >= cap ? "bg-red-500" : used >= cap * 0.8 ? "bg-amber-500" : TRACK_COLORS[track]
                        }`}
                        style={{ width: `${Math.min((used / cap) * 100, 100)}%` }}
                      />
                    </div>
                  )}
                </div>

                {/* Post cards */}
                <div className="space-y-2 min-h-[100px]">
                  {(!sortedPosts || sortedPosts.length === 0) && (
                    <div className="text-center py-6">
                      <p className="text-xs text-gray-400 mb-2">No posts in queue.</p>
                      <button
                        onClick={() => router.push("/dashboard/compose")}
                        className="text-xs text-blue-600 hover:text-blue-700 hover:underline font-medium"
                      >
                        <PenLine className="h-3 w-3 inline mr-1" />
                        Create a post to get started
                      </button>
                    </div>
                  )}
                  {sortedPosts.map((post, index) => (
                    <Card
                      key={post.id}
                      className="p-3 border border-gray-200 rounded-lg shadow-none bg-white"
                    >
                      <div className="flex items-start gap-2">
                        {/* Position number */}
                        <span className="text-xs font-bold text-gray-400 mt-0.5 shrink-0 w-5 text-center" data-testid={`queue-position-${index + 1}`}>
                          {post.queuePosition ?? index + 1}
                        </span>
                        <div className="flex-1 min-w-0">
                          <p className="text-xs text-gray-800 line-clamp-2 mb-2">
                            {post.content.length > 80
                              ? post.content.slice(0, 80) + "..."
                              : post.content}
                          </p>
                          <div className="flex items-center gap-1.5 flex-wrap">
                            <Badge
                              className={`text-[10px] px-1.5 py-0 rounded-full ${
                                post.status === "PENDING_APPROVAL"
                                  ? "bg-yellow-100 text-yellow-700"
                                  : "bg-green-100 text-green-700"
                              }`}
                            >
                              {post.status}
                            </Badge>
                            {post.region && (
                              <RegionBadge region={post.region} />
                            )}
                            {post.publishPriority !== "NORMAL" && (
                              <Badge className="text-[10px] px-1.5 py-0 rounded-full bg-red-100 text-red-700">
                                {post.publishPriority}
                              </Badge>
                            )}
                            {post.originalScheduledAt && post.scheduledAt && post.originalScheduledAt !== post.scheduledAt && (
                              <Badge className="text-[10px] px-1.5 py-0 rounded-full bg-purple-100 text-purple-700" data-testid="rescheduled-badge">
                                ↻ rescheduled
                              </Badge>
                            )}
                          </div>
                          {/* Bug fix: Show original schedule date for rescheduled posts */}
                          {post.originalScheduledAt && post.scheduledAt && post.originalScheduledAt !== post.scheduledAt && (
                            <p className="text-[10px] text-purple-400 mt-0.5" data-testid="original-schedule">
                              Originally: {new Date(post.originalScheduledAt).toLocaleString(undefined, { timeZoneName: 'short' })}
                            </p>
                          )}
                          {/* Bug fix: Per-network publish status */}
                          {post.postAccounts && post.postAccounts.length > 0 && (
                            <div className="mt-1 space-y-0.5">
                              {post.postAccounts.map((pa) => (
                                <div key={pa.socialAccount.id} className="flex items-center gap-1 text-[10px]" data-testid="network-status">
                                  <span className="font-medium text-gray-500">{pa.socialAccount.network}:</span>
                                  <span className={pa.publishStatus === "PUBLISHED" ? "text-green-600" : pa.publishStatus === "FAILED" ? "text-red-600" : "text-amber-500"}>
                                    {pa.publishStatus}
                                  </span>
                                </div>
                              ))}
                            </div>
                          )}
                          {post.scheduledAt && (
                            <p className="text-[10px] text-gray-400 mt-1">
                              {new Date(post.scheduledAt).toLocaleString(undefined, { timeZoneName: 'short' })}
                            </p>
                          )}
                          <p className="text-[10px] text-gray-400">
                            by {post.author?.name ?? post.author?.email}
                          </p>
                          <div className="flex gap-1.5 mt-2 flex-wrap">
                            {/* Reorder buttons */}
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-8 w-8 sm:h-6 sm:w-6 p-0 text-xs border-gray-200 text-gray-500 hover:bg-gray-50"
                              onClick={() => handleReorder(post.id, post.queuePosition ?? index + 1, "up")}
                              disabled={index === 0}
                              title="Move up"
                              aria-label="Move up"
                            >
                              <ArrowUp className="h-3 w-3" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-8 w-8 sm:h-6 sm:w-6 p-0 text-xs border-gray-200 text-gray-500 hover:bg-gray-50"
                              onClick={() => handleReorder(post.id, post.queuePosition ?? index + 1, "down")}
                              disabled={index === (data?.posts?.length ?? 1) - 1}
                              title="Move down"
                              aria-label="Move down"
                            >
                              <ArrowDown className="h-3 w-3" />
                            </Button>
                            {post.status === "PENDING_APPROVAL" && (
                              <Button
                                size="sm"
                                onClick={() => handleApprove(post.id)}
                                className="h-8 sm:h-6 text-xs bg-green-600 hover:bg-green-700 text-white flex-1"
                              >
                                Approve
                              </Button>
                            )}
                            {!["PUBLISHED", "FAILED"].includes(post.status) && (
                              <>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  className="h-8 w-8 sm:h-6 sm:w-6 p-0 text-xs border-gray-200 text-gray-600 hover:bg-gray-50"
                                  onClick={() => router.push(`/dashboard/compose?edit=${post.id}`)}
                                >
                                  <PenSquare className="h-3 w-3" />
                                </Button>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  className="h-8 w-8 sm:h-6 sm:w-6 p-0 text-xs border-gray-200 text-red-500 hover:bg-red-50 hover:border-red-200"
                                  onClick={() => handleDelete(post.id)}
                                >
                                  <Trash2 className="h-3 w-3" />
                                </Button>
                              </>
                            )}
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>
            );
          })}
          {/* All posts must be in a track queue — no "unqueued" section */}
        </div>
      )}
    </div>
  );
}
