"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ClipboardCheck, Globe } from "lucide-react";
import type { UserRole, ContentTrack, Region } from "@/lib/types";
import { TRACK_LABELS } from "@/lib/track-display";

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

const REGION_LABELS: Record<Region, string> = {
  APAC: "APAC",
  NA: "NA",
  LATAM: "LATAM",
  EMEA: "EMEA",
  GLOBAL: "Global",
};

const REGION_COLORS: Record<Region, string> = {
  APAC: "bg-teal-100 text-teal-700",
  NA: "bg-sky-100 text-sky-700",
  LATAM: "bg-purple-100 text-purple-700",
  EMEA: "bg-amber-100 text-amber-700",
  GLOBAL: "bg-gray-100 text-gray-700",
};

interface PendingPost {
  id: string;
  content: string;
  networks: string[];
  track: ContentTrack | null;
  region: Region | null;
  scheduledAt: string | null;
  createdAt: string;
  author: {
    id: string;
    name: string | null;
    email: string;
    image: string | null;
  };
}

export default function ApprovalsPage() {
  const { data: session, status } = useSession();
  const role = (session?.user as { role?: UserRole })?.role;

  const [posts, setPosts] = useState<PendingPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [rejectId, setRejectId] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState("");
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [regionFilter, setRegionFilter] = useState<Region | "">("");
  const [filterRegions, setFilterRegions] = useState<string[]>([]);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [bulkLoading, setBulkLoading] = useState(false);

  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 fetchPending = async (region?: Region | "") => {
    try {
      const params = region ? `?region=${region}` : "";
      const res = await fetch(`/api/v1/posts/pending${params}`);
      if (res.ok) {
        const data = await res.json();
        setPosts(data);
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPending(regionFilter);
  }, [regionFilter]);

  const toggleSelected = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const handleBulkApprove = async () => {
    if (selectedIds.size === 0) return;
    if (!window.confirm(`Approve ${selectedIds.size} selected post(s)?`)) return;
    setBulkLoading(true);
    let approved = 0;
    for (const postId of selectedIds) {
      try {
        const res = await fetch(`/api/v1/posts/${postId}/approve`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        });
        if (res.ok) approved++;
      } catch { /* continue */ }
    }
    setPosts((prev) => prev.filter((p) => !selectedIds.has(p.id)));
    setSelectedIds(new Set());
    setBulkLoading(false);
    if (approved > 0) window.dispatchEvent(new CustomEvent("approvals-changed"));
  };

  const handleApprove = async (postId: string) => {
    if (!window.confirm("Are you sure you want to approve this post? It will be queued for publishing.")) {
      return;
    }
    setActionLoading(postId);
    try {
      const res = await fetch(`/api/v1/posts/${postId}/approve`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
      });
      if (res.ok) {
        setPosts((prev) => prev.filter((p) => p.id !== postId));
        window.dispatchEvent(new CustomEvent("approvals-changed"));
      }
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (postId: string) => {
    if (!rejectReason.trim()) return;
    setActionLoading(postId);
    try {
      const res = await fetch(`/api/v1/posts/${postId}/reject`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reason: rejectReason }),
      });
      if (res.ok) {
        setPosts((prev) => prev.filter((p) => p.id !== postId));
        setRejectId(null);
        setRejectReason("");
        window.dispatchEvent(new CustomEvent("approvals-changed"));
      }
    } finally {
      setActionLoading(null);
    }
  };

  if (status === "loading") {
    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="h-7 w-32 bg-gray-100 rounded animate-pulse" />
          <div className="h-4 w-56 bg-gray-100 rounded animate-pulse mt-2" />
        </div>
        <div className="space-y-4">
          {Array.from({ length: 2 }).map((_, i) => (
            <div key={i} className="rounded-xl border border-gray-200 p-6 space-y-3">
              <div className="h-4 w-24 bg-gray-100 rounded animate-pulse" />
              <div className="h-16 w-full bg-gray-100 rounded animate-pulse" />
              <div className="h-8 w-40 bg-gray-100 rounded animate-pulse" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  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 items-center justify-between">
          <div>
            <h1 className="text-2xl font-semibold text-gray-900">Approvals</h1>
            <p className="text-sm text-gray-500">Review and approve pending posts</p>
          </div>
          <div className="flex items-center gap-3">
            {selectedIds.size > 0 && (
              <Button
                size="sm"
                onClick={handleBulkApprove}
                disabled={bulkLoading}
                className="bg-green-600 hover:bg-green-700 text-white text-xs"
              >
                {bulkLoading ? "Approving..." : `Approve Selected (${selectedIds.size})`}
              </Button>
            )}
            <Select value={regionFilter || "all"} onValueChange={(v) => { setLoading(true); setRegionFilter(v === "all" ? "" : v as Region); }}>
              <SelectTrigger className="w-[140px] h-8 text-xs border-gray-200" data-testid="approvals-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>
          </div>
        </div>
      </div>

      {loading ? (
        <div className="text-sm text-gray-500">Loading...</div>
      ) : posts.length === 0 ? (
        <div className="rounded-lg border border-dashed border-gray-300 bg-gray-50 p-12 text-center">
          <ClipboardCheck className="mx-auto h-10 w-10 text-gray-300 mb-3" />
          <p className="text-sm font-medium text-gray-600">No posts waiting for approval</p>
          <p className="text-xs text-gray-400 mt-1">
            Posts from tracks that require approval will appear here for review.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {posts.map((post) => (
            <Card key={post.id} className="bg-white border border-gray-200 rounded-xl shadow-none">
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={selectedIds.has(post.id)}
                      onChange={() => toggleSelected(post.id)}
                      className="rounded border-gray-300"
                    />
                    <CardTitle className="text-sm font-medium text-gray-900">
                      {post.networks.join(", ")}
                    </CardTitle>
                    {post.track && (
                      <Badge className={`text-[10px] px-1.5 py-0 rounded-full ${TRACK_COLORS[post.track]}`}>
                        {TRACK_LABELS[post.track]}
                      </Badge>
                    )}
                    {post.region && (
                      <Badge className={`text-[10px] px-1.5 py-0 rounded-full ${REGION_COLORS[post.region]}`}>
                        {REGION_LABELS[post.region]}
                      </Badge>
                    )}
                  </div>
                  <span className="text-xs text-gray-400">
                    {new Date(post.createdAt).toLocaleDateString()}
                  </span>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <p className="text-sm text-gray-700 whitespace-pre-wrap">
                  {post.content.length > 300 ? post.content.slice(0, 300) + "..." : post.content}
                </p>

                {/* Submitter & schedule info */}
                <div className="flex items-center gap-4 text-xs text-gray-500">
                  <div className="flex items-center gap-1.5">
                    <Avatar className="h-5 w-5">
                      <AvatarImage src={post.author.image || undefined} />
                      <AvatarFallback className="bg-gray-100 text-[8px] text-gray-600">
                        {(post.author.name || post.author.email).slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <span>{post.author.name || post.author.email}</span>
                  </div>
                  {post.scheduledAt && (
                    <span>
                      Scheduled: {new Date(post.scheduledAt).toLocaleString(undefined, { timeZoneName: 'short' })}
                    </span>
                  )}
                </div>

                {/* Reject modal inline */}
                {rejectId === post.id ? (
                  <div className="space-y-2 bg-red-50 rounded-lg p-3 border border-red-100">
                    <p className="text-xs font-medium text-red-700">Rejection reason (required)</p>
                    <textarea
                      value={rejectReason}
                      onChange={(e) => setRejectReason(e.target.value)}
                      placeholder="Explain why this post is being rejected..."
                      className="w-full min-h-[60px] rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-400 resize-y"
                    />
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        onClick={() => handleReject(post.id)}
                        disabled={!rejectReason.trim() || actionLoading === post.id}
                        className="bg-red-600 hover:bg-red-700 text-white text-xs"
                      >
                        {actionLoading === post.id ? "..." : "Confirm Reject"}
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => { setRejectId(null); setRejectReason(""); }}
                        className="text-xs"
                      >
                        Cancel
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div className="flex gap-2">
                    <Button
                      size="sm"
                      onClick={() => handleApprove(post.id)}
                      disabled={actionLoading === post.id}
                      className="bg-green-600 hover:bg-green-700 text-white text-xs"
                    >
                      {actionLoading === post.id ? "..." : "Approve"}
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => setRejectId(post.id)}
                      className="text-xs border-red-200 text-red-600 hover:bg-red-50"
                    >
                      Reject
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
