"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useSelector } from "react-redux";
import type { RootState } from "@/state/store";
import type { DashboardEnquiryItem } from "@/types/dashboard";
import { EyeViewIcon, LensThumb, SortIcon } from "./icons";
import ProductImage from "../common/ProductImage";
import { formatListingNo } from "@/lib/listingNo";

type SortKey = "id" | "product" | "buyer";
type SortDir = "asc" | "desc";

const COLUMNS: { key: SortKey; label: string }[] = [
  { key: "id", label: "ID" },
  { key: "product", label: "Product" },
  { key: "buyer", label: "Asked by" },
];

export default function RecentQuestionsTable() {
  const router = useRouter();
  const { enquiries, loading } = useSelector((state: RootState) => state.dashboard);
  const [sortKey, setSortKey] = useState<SortKey | null>(null);
  const [sortDir, setSortDir] = useState<SortDir>("asc");

  const handleSort = (key: SortKey) => {
    if (sortKey === key) {
      setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortKey(key);
      setSortDir("asc");
    }
  };

  const sortedEnquiries = useMemo(() => {
    if (!sortKey) return enquiries;
    const list = [...enquiries];
    list.sort((a, b) => {
      if (sortKey === "id") {
        const aNum = a.product?.listingNo ?? 0;
        const bNum = b.product?.listingNo ?? 0;
        if (aNum !== 0 || bNum !== 0) {
          return sortDir === "asc" ? aNum - bNum : bNum - aNum;
        }
        return sortDir === "asc" ? a.id.localeCompare(b.id) : b.id.localeCompare(a.id);
      }
      if (sortKey === "product") {
        const aTitle = (a.product?.title || "").toLowerCase();
        const bTitle = (b.product?.title || "").toLowerCase();
        return sortDir === "asc" ? aTitle.localeCompare(bTitle) : bTitle.localeCompare(aTitle);
      }
      if (sortKey === "buyer") {
        const aName = `${a.buyer?.firstName || ""} ${a.buyer?.lastName || ""}`.trim().toLowerCase();
        const bName = `${b.buyer?.firstName || ""} ${b.buyer?.lastName || ""}`.trim().toLowerCase();
        return sortDir === "asc" ? aName.localeCompare(bName) : bName.localeCompare(aName);
      }
      return 0;
    });
    return list;
  }, [enquiries, sortKey, sortDir]);

  return (
    <div className="flex h-[420px] min-w-0 flex-col overflow-hidden rounded-xl border border-[#E4E7EC] bg-white">
      <div className="flex flex-shrink-0 items-center justify-between border-b border-[#E4E7EC] px-5 py-4">
        <h2 className="text-[16px] font-semibold text-[#101828]">Recent Asked Questions</h2>
        <Link href="/questions" className="text-[13px] font-medium text-[#1657D9] hover:underline">
          View All
        </Link>
      </div>

      <div className="thin-scrollbar min-h-0 flex-1 overflow-y-auto">
        {loading.enquiries ? (
          <div className="space-y-3 p-5">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-10 animate-pulse rounded bg-[#F2F4F7]" />
            ))}
          </div>
        ) : sortedEnquiries.length === 0 ? (
          <div className="flex h-full items-center justify-center p-8 text-center text-[13px] text-[#667085]">
            No recent questions available.
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="sticky top-0 z-10">
              <tr className="border-b border-[#E4E7EC] bg-[#EAF1FF]">
                {COLUMNS.map(({ key, label }) => (
                  <th
                    key={key}
                    onClick={() => handleSort(key)}
                    className="cursor-pointer select-none whitespace-nowrap px-5 py-3 text-left text-[13px] font-medium text-[#475467] hover:text-[#101828]"
                  >
                    <span className="flex w-full items-center justify-between">
                      {label}
                      <SortIcon className={sortKey === key ? "text-[#1657D9]" : "opacity-60"} />
                    </span>
                  </th>
                ))}
                <th className="whitespace-nowrap px-5 py-3 text-left text-[13px] font-medium text-[#475467]">
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {sortedEnquiries.map((row) => {
                const buyerName = row.buyer
                  ? `${row.buyer.firstName || ""} ${row.buyer.lastName || ""}`.trim() || "Unknown"
                  : "Unknown";
                const buyerEmail = row.buyer?.email || "—";
                const productTitle = row.product?.title || "Unknown Product";
                const displayId = formatListingNo(row.product?.listingNo);

                return (
                  <tr key={row.id} className="border-b border-[#F2F4F7] last:border-b-0 hover:bg-[#F9FBFF]">
                    <td className="whitespace-nowrap px-5 py-3">
                      <span className="text-[14px] font-medium text-[#1657D9]">{displayId}</span>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-2.5">
                        <ProductImage
                          src={row.product?.images?.[0]}
                          alt={productTitle}
                        />
                        <span className="max-w-[160px] truncate text-[14px] text-[#344054]">{productTitle}</span>
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-5 py-3">
                      <p className="text-[14px] text-[#101828]">{buyerName}</p>
                      <p className="text-[12px] text-[#1657D9]">{buyerEmail}</p>
                    </td>
                    <td className="whitespace-nowrap px-5 py-3">
                      <button
                        type="button"
                        onClick={() => router.push(`/questions?id=${encodeURIComponent(row.id)}`)}
                        className="flex items-center gap-1.5 text-[13px] text-[#475467] hover:text-[#1657D9]"
                      >
                        <EyeViewIcon />
                        View
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
