"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "sonner";
import { useClickOutside } from "@/hooks/useClickOutside";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { fetchSellerById, changeSellerStatus } from "@/state/seller/sellerSlice";
import { getImageUrl } from "@/lib/imageUrl";
import AvatarImage from "../common/AvatarImage";
import StatusBadge from "../common/StatusBadge";
import {
  ArrowLeftIcon,
  KebabIcon,
  PersonCheckIcon,
  PersonXIcon,
  PowerIcon,
} from "../dashboard/icons";
import SuspendSellerModal from "./SuspendSellerModal";
import ReactivateSellerModal from "./ReactivateSellerModal";
import ListedProductsTable from "./ListedProductsTable";

const statusConfig: Record<string, { text: string; dot: string }> = {
  Active: { text: "#16A34A", dot: "#16A34A" },
  active: { text: "#16A34A", dot: "#16A34A" },
  Suspended: { text: "#DC2626", dot: "#DC2626" },
  suspended: { text: "#DC2626", dot: "#DC2626" },
  Inactive: { text: "#98A2B3", dot: "#98A2B3" },
  inactive: { text: "#98A2B3", dot: "#98A2B3" },
};

function getInitials(name?: string) {
  if (!name) return "S";
  return name
    .split(" ")
    .filter(Boolean)
    .map((part) => part[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();
}

export default function SellerDetailView({ sellerId }: { sellerId: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useAppDispatch();

  const { currentSeller, sellerLoading, sellerError, actionLoading } = useAppSelector(
    (state) => state.seller
  );

  const [tab, setTab] = useState<"overview" | "products">(
    searchParams.get("tab") === "products" ? "products" : "overview"
  );
  const [menuOpen, setMenuOpen] = useState(false);
  const [suspendOpen, setSuspendOpen] = useState(false);
  const [reactivateOpen, setReactivateOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement | null>(null);

  useClickOutside(menuRef, () => setMenuOpen(false), menuOpen);

  useEffect(() => {
    if (sellerId) {
      dispatch(fetchSellerById(sellerId));
    }
  }, [dispatch, sellerId]);

  const selectTab = (next: "overview" | "products") => {
    setTab(next);
    const params = new URLSearchParams(searchParams.toString());
    if (next === "products") params.set("tab", "products");
    else params.delete("tab");
    const query = params.toString();
    router.replace(`/sellers/${sellerId}${query ? `?${query}` : ""}`, { scroll: false });
  };

  const handleInactivate = async () => {
    setMenuOpen(false);
    try {
      await dispatch(
        changeSellerStatus({
          sellerIds: [sellerId],
          status: "inactive",
        })
      ).unwrap();
      toast.success("Seller inactivated successfully");
    } catch (err: any) {
      toast.error(err || "Failed to inactivate seller");
    }
  };

  const handleSuspendConfirm = async (reasons: string[], note: string) => {
    const isOther = reasons.includes("Other");
    const primaryReason = reasons[0] || "Administrative suspension";
    try {
      await dispatch(
        changeSellerStatus({
          sellerIds: [sellerId],
          status: "suspended",
          reason: primaryReason,
          reasonMessage: isOther ? note : note || undefined,
        })
      ).unwrap();
      toast.success("Seller suspended successfully");
      setSuspendOpen(false);
    } catch (err: any) {
      toast.error(err || "Failed to suspend seller");
    }
  };

  const handleReactivateConfirm = async () => {
    try {
      await dispatch(
        changeSellerStatus({
          sellerIds: [sellerId],
          status: "active",
        })
      ).unwrap();
      toast.success("Seller reactivated successfully");
      setReactivateOpen(false);
    } catch (err: any) {
      toast.error(err || "Failed to reactivate seller");
    }
  };

  if (sellerLoading && !currentSeller) {
    return (
      <div className="flex h-64 flex-col items-center justify-center gap-3">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-[#1657D9] border-t-transparent" />
        <p className="text-[14px] text-[#667085]">Loading seller details...</p>
      </div>
    );
  }

  if (sellerError && !currentSeller) {
    return (
      <div className="flex h-64 flex-col items-center justify-center gap-4">
        <p className="text-[14px] font-medium text-[#DC2626]">{sellerError}</p>
        <button
          type="button"
          onClick={() => router.push("/sellers")}
          className="rounded-lg bg-[#1657D9] px-4 py-2 text-[13px] font-medium text-white hover:bg-[#1245AB]"
        >
          Back to Sellers
        </button>
      </div>
    );
  }

  const seller = currentSeller || {
    id: sellerId,
    name: "Seller",
    handle: "",
    email: "",
    phone: "-",
    location: "-",
    products: 0,
    status: "Active" as const,
  };

  const isActive = (seller.status || "").toLowerCase() === "active";
  const avatarImage = seller.profileImage ? getImageUrl(seller.profileImage) : null;

  const contactDetails = [
    { label: "Formatted Name", value: `${seller.name} ${seller.handle ? `(${seller.handle})` : ""}`.trim() },
    { label: "Email Address", value: seller.email || "-" },
    { label: "Phone Number", value: seller.phone || "-" },
    ...(seller.companyName ? [{ label: "Company Name", value: seller.companyName }] : []),
    ...(seller.australianABN ? [{ label: "Australian ABN", value: seller.australianABN }] : []),
    { label: "Address", value: seller.address || seller.businessAddress || "-" },
    { label: "City / Town", value: seller.city || seller.businessCity || "-" },
    { label: "State / Province", value: seller.state || seller.businessState || "-" },
    { label: "Country", value: seller.country || seller.businessCountry || "-" },
    { label: "Postcode / Zip", value: seller.postcode || seller.postalCode || seller.businessPostalCode || "-" },
  ];

  return (
    <div className="min-w-0">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => router.push("/sellers")}
            className="flex h-9 w-9 items-center justify-center rounded-full border border-[#E4E7EC] text-[#344054] transition-colors hover:bg-[#F5F7F9]"
            aria-label="Back to Sellers"
          >
            <ArrowLeftIcon />
          </button>

          <div className="flex gap-1 rounded-full bg-[#F2F4F7] p-1 text-[13px]">
            <button
              type="button"
              onClick={() => selectTab("overview")}
              className={`rounded-full px-4 py-1.5 font-medium transition-colors ${
                tab === "overview" ? "bg-white text-[#1657D9] shadow-sm" : "text-[#667085]"
              }`}
            >
              Overview
            </button>
            <button
              type="button"
              onClick={() => selectTab("products")}
              className={`rounded-full px-4 py-1.5 font-medium transition-colors ${
                tab === "products" ? "bg-white text-[#1657D9] shadow-sm" : "text-[#667085]"
              }`}
            >
              Listed Products
            </button>
          </div>
        </div>

        <div ref={menuRef} className="relative">
          <button
            type="button"
            onClick={() => setMenuOpen((prev) => !prev)}
            className="flex h-9 w-9 items-center justify-center rounded-full bg-[#F2F4F7] text-[#475467] transition-colors hover:bg-[#E4E7EC]"
            aria-label="Seller actions"
          >
            <KebabIcon />
          </button>

          {menuOpen && (
            <div className="absolute right-0 top-[calc(100%+8px)] z-20 min-w-[180px] rounded-lg border border-[#E4E7EC] bg-white py-1.5 shadow-[0_10px_24px_rgba(15,23,42,0.12)]">
              {isActive ? (
                <>
                  <button
                    type="button"
                    onClick={handleInactivate}
                    disabled={actionLoading}
                    className="flex w-full items-center gap-2.5 whitespace-nowrap px-3.5 py-2 text-left text-[13px] font-medium text-[#344054] hover:bg-[#F5F7F9] disabled:opacity-50"
                  >
                    <PowerIcon />
                    Inactivate Seller
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setMenuOpen(false);
                      setSuspendOpen(true);
                    }}
                    disabled={actionLoading}
                    className="flex w-full items-center gap-2.5 whitespace-nowrap px-3.5 py-2 text-left text-[13px] font-medium text-[#DC2626] hover:bg-[#F5F7F9] disabled:opacity-50"
                  >
                    <PersonXIcon />
                    Suspend Seller
                  </button>
                </>
              ) : (
                <button
                  type="button"
                  onClick={() => {
                    setMenuOpen(false);
                    setReactivateOpen(true);
                  }}
                  disabled={actionLoading}
                  className="flex w-full items-center gap-2.5 whitespace-nowrap px-3.5 py-2 text-left text-[13px] font-medium text-[#16A34A] hover:bg-[#F5F7F9] disabled:opacity-50"
                >
                  <PersonCheckIcon />
                  Reactivate Seller
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      <h1 className="mt-5 text-[20px] font-bold text-[#101828]">
        {tab === "overview" ? "Seller Overview" : "Listed Products"}
      </h1>

      {tab === "overview" ? (
        <>
          <p className="mt-4 text-[13px] font-medium text-[#475467]">Profile Photo</p>

          <div className="mt-3 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="flex h-16 w-16 items-center justify-center overflow-hidden rounded-full bg-[#EAF1FF] text-[20px] font-semibold text-[#1657D9] border border-[#E4E7EC]">
                <AvatarImage
                  src={seller.profileImage}
                  alt={seller.name}
                  initials={getInitials(seller.name)}
                />
              </div>
              <div>
                <p className="text-[16px] font-semibold text-[#101828]">{seller.name}</p>
                {seller.handle && (
                  <p className="text-[13px] text-[#1657D9]">({seller.handle})</p>
                )}
                <div className="mt-1 flex flex-wrap items-center gap-5 text-[12px] text-[#667085]">
                  <span>
                    Member Since:{" "}
                    <span className="text-[#101828]">
                      {seller.memberSince || seller.joinedOn || "-"}
                    </span>
                  </span>
                  <span>
                    Total Products:{" "}
                    <span className="text-[#101828]">
                      {seller.products ?? seller.totalProducts ?? 0}
                    </span>
                  </span>
                </div>
              </div>
            </div>

            <StatusBadge status={seller.status} colorMap={statusConfig} />
          </div>

          <div className="mt-6 overflow-hidden rounded-xl border border-[#E4E7EC]">
            <div className="border-b border-[#E4E7EC] bg-white px-5 py-3">
              <h2 className="text-[14px] font-semibold text-[#101828]">Contact Information</h2>
            </div>
            <div>
              {contactDetails.map((item, index) => (
                <div
                  key={item.label}
                  className={`grid grid-cols-[220px_1fr] px-5 py-3 text-[13px] ${
                    index % 2 === 0 ? "bg-[#F5F7F9]" : "bg-white"
                  }`}
                >
                  <span className="text-[#667085]">{item.label}</span>
                  <span className="font-medium text-[#101828]">{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </>
      ) : (
        <div className="mt-6">
          <ListedProductsTable sellerId={sellerId} />
        </div>
      )}

      <SuspendSellerModal
        open={suspendOpen}
        count={1}
        loading={actionLoading}
        onClose={() => setSuspendOpen(false)}
        onConfirm={handleSuspendConfirm}
      />

      <ReactivateSellerModal
        open={reactivateOpen}
        count={1}
        loading={actionLoading}
        onClose={() => setReactivateOpen(false)}
        onConfirm={handleReactivateConfirm}
      />
    </div>
  );
}
