"use client";

import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { Linkedin, Twitter, Facebook, Instagram, MessageSquare, Inbox as InboxIcon } from "lucide-react";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { InboxItem } from "@/components/inbox/InboxItem";
import type { Network, EngagementType, EngagementStatus, UserRole } from "@/lib/types";

type FilterNetwork = Network | "ALL";
type FilterStatus = EngagementStatus | "ALL" | "READ";

interface EngagementItemData {
  id: string;
  authorName: string;
  network: Network;
  type: EngagementType;
  content: string;
  status: EngagementStatus;
  createdAt: string;
  postContent?: string;
}

const NETWORK_FILTERS: { value: FilterNetwork; label: string; icon?: typeof Linkedin }[] = [
  { value: "ALL", label: "All Networks" },
  { value: "LINKEDIN", label: "LinkedIn", icon: Linkedin },
  { value: "TWITTER", label: "Twitter", icon: Twitter },
  { value: "FACEBOOK", label: "Facebook", icon: Facebook },
  { value: "INSTAGRAM", label: "Instagram", icon: Instagram },
];

const STATUS_FILTERS: { value: FilterStatus; label: string }[] = [
  { value: "ALL", label: "All" },
  { value: "UNREAD", label: "Unread" },
  { value: "READ", label: "Read" },
  { value: "REPLIED", label: "Replied" },
];

export default function InboxPage() {
  const { data: session } = useSession();
  const role = (session?.user as { role?: UserRole })?.role;
  const isViewer = role === "VIEWER";

  const [networkFilter, setNetworkFilter] = useState<FilterNetwork>("ALL");
  const [statusFilter, setStatusFilter] = useState<FilterStatus>("ALL");
  const [items, setItems] = useState<EngagementItemData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const fetchItems = useCallback(async () => {
    try {
      setError("");
      const params = new URLSearchParams();
      if (networkFilter !== "ALL") params.set("network", networkFilter);
      // "READ" maps to IGNORED on the backend (we treat IGNORED as "read/dismissed")
      if (statusFilter !== "ALL" && statusFilter !== "READ") {
        params.set("status", statusFilter);
      }
      const qs = params.toString();
      const res = await fetch(`/api/v1/inbox${qs ? `?${qs}` : ""}`);
      if (!res.ok) throw new Error("Failed to load inbox");
      const data = await res.json();
      setItems(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load inbox");
    } finally {
      setLoading(false);
    }
  }, [networkFilter, statusFilter]);

  useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  // Client-side filter for "READ" status (items that are IGNORED = read/dismissed)
  const filtered = statusFilter === "READ"
    ? items.filter((i) => i.status === "IGNORED")
    : items;

  const unreadCount = items.filter((i) => i.status === "UNREAD").length;

  const handleReply = async (id: string, content: string) => {
    try {
      const res = await fetch(`/api/v1/inbox/${id}/reply`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content }),
      });
      if (!res.ok) throw new Error("Failed to send reply");
      // Update local state
      setItems((prev) =>
        prev.map((item) =>
          item.id === id ? { ...item, status: "REPLIED" as EngagementStatus } : item
        )
      );
    } catch (err) {
      alert(err instanceof Error ? err.message : "Failed to send reply");
    }
  };

  const handleMarkRead = async (id: string) => {
    try {
      const res = await fetch(`/api/v1/inbox/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "IGNORED" }),
      });
      if (!res.ok) throw new Error("Failed to mark as read");
      setItems((prev) =>
        prev.map((item) =>
          item.id === id ? { ...item, status: "IGNORED" as EngagementStatus } : item
        )
      );
    } catch (err) {
      alert(err instanceof Error ? err.message : "Failed to mark as read");
    }
  };

  const handleIgnore = async (id: string) => {
    try {
      const res = await fetch(`/api/v1/inbox/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "IGNORED" }),
      });
      if (!res.ok) throw new Error("Failed to ignore");
      setItems((prev) =>
        prev.map((item) =>
          item.id === id ? { ...item, status: "IGNORED" as EngagementStatus } : item
        )
      );
    } catch (err) {
      alert(err instanceof Error ? err.message : "Failed to ignore item");
    }
  };

  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">
        <h1 className="text-2xl font-semibold text-gray-900">Engagement Inbox</h1>
        <p className="text-sm text-gray-500">Manage comments, mentions, and direct messages</p>
      </div>

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

      <div className="flex flex-col gap-6 lg:flex-row">
        {/* Filter sidebar */}
        <div className="w-full shrink-0 space-y-4 lg:w-48">
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-2">Network</p>
            <div className="space-y-0.5">
              {NETWORK_FILTERS.map(({ value, label, icon: Icon }) => (
                <button
                  key={value}
                  onClick={() => setNetworkFilter(value)}
                  className={`flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors ${
                    networkFilter === value ? "bg-primary text-primary-foreground" : "hover:bg-muted"
                  }`}
                >
                  {Icon && <Icon className="h-3.5 w-3.5" />}
                  {label}
                </button>
              ))}
            </div>
          </div>
          <Separator />
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-2">Status</p>
            <div className="space-y-0.5">
              {STATUS_FILTERS.map(({ value, label }) => (
                <button
                  key={value}
                  onClick={() => setStatusFilter(value)}
                  className={`flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors ${
                    statusFilter === value ? "bg-primary text-primary-foreground" : "hover:bg-muted"
                  }`}
                >
                  {label}
                  {value === "UNREAD" && unreadCount > 0 && (
                    <span className="ml-auto rounded-full bg-blue-500 px-1.5 text-[10px] text-white">
                      {unreadCount}
                    </span>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Items list */}
        <div className="flex-1 space-y-2">
          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 4 }).map((_, i) => (
                <Skeleton key={i} className="h-16 w-full rounded-lg" />
              ))}
            </div>
          ) : filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16">
              <InboxIcon className="h-12 w-12 text-muted-foreground/30 mb-4" />
              <p className="text-sm font-medium text-muted-foreground">No new engagements</p>
              <p className="text-xs text-muted-foreground mt-1 max-w-xs text-center">
                {networkFilter !== "ALL" || statusFilter !== "ALL"
                  ? "Try adjusting your filters"
                  : "Once you publish posts, comments, mentions, and DMs from your audience will appear here."}
              </p>
            </div>
          ) : (
            filtered.map((item) => (
              <InboxItem
                key={item.id}
                {...item}
                readOnly={isViewer}
                onReply={handleReply}
                onMarkRead={handleMarkRead}
                onIgnore={handleIgnore}
              />
            ))
          )}
        </div>
      </div>
    </div>
  );
}
