"use client";

import { useState } from "react";
import { Button } from "@heroui/react";
import { useTranslations, useLocale } from "next-intl";
import { useRouter } from "next/navigation";
import {
  useLiveListings,
  useOffer,
  useDeleteListing,
  type Listing,
} from "@/lib/clientQueries";
import { parseMoneyValue } from "@/lib/moneyParse";
import OfferClient from "@/(pages)/autionClient/OfferClient";
import { Trash2 } from "lucide-react";
import { useAppToast } from "@/app/[lang]/providers";
import AtayaLoader from "@/components/loaders/AtayaLoader";
function listingSaleAmount(l: Listing): number | undefined {
  return parseMoneyValue(l.price) ?? parseMoneyValue(l.total_price);
}

function Badge({ state, label }: { state: string; label: string }) {
  const classes: Record<string, string> = {
    pending: "bg-amber-500 text-white",
    sold: "bg-slate-500 text-white",
    active: "bg-green-500 text-white",
    inactive: "bg-slate-400 text-white",
    rejected: "bg-rose-600 text-white",
  };

  return (
    <span
      className={`px-2 py-1 rounded-lg text-xs font-bold ${
        classes[state] || "bg-slate-200"
      }`}
    >
      {label}
    </span>
  );
}
export default function LiveListingsTable() {
  const t = useTranslations("DASHBOARD.LISTINGS");
  const lang = useLocale();
  const router = useRouter();
  const toast = useAppToast();
  const [selectedListingId, setSelectedListingId] = useState<string | null>(
    null,
  );
  const [search, setSearch] = useState("");
  const [status, setStatus] = useState<string>("");
  const [animalType, setAnimalType] = useState<string>("");
  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useLiveListings({
      status: status || undefined,
      animal_type: animalType || undefined,
    });
  const deleteListing = useDeleteListing();
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const listings = data?.pages.flatMap((p) => p.data) ?? [];

  const {
    data: offerDetails,
    isLoading: loadingDetails,
    error: detailsError,
  } = useOffer(selectedListingId || undefined);

  const filteredListings = listings.filter((l) => {
    if (!search) return true;
    const term = search.toLowerCase();
    return (
      String(l.id).toLowerCase().includes(term) ||
      l.title?.toLowerCase().includes(term) ||
      l.description?.toLowerCase().includes(term) ||
      l.animal_type?.toLowerCase().includes(term) ||
      l.status?.toLowerCase().includes(term) ||
      String(l.price ?? l.total_price ?? "")
        .toLowerCase()
        .includes(term)
    );
  });
  if (selectedListingId) {
    if (loadingDetails) {
      return <AtayaLoader />;
    }

    if (detailsError) {
      return (
        <div className="space-y-4">
          <div>
            <div className="text-center p-8 text-red-500">
              ⚠️ حدث خطأ أثناء تحميل تفاصيل العرض.
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="p-4">
        <Button
          color="secondary"
          variant="flat"
          className="mb-4"
          onPress={() => setSelectedListingId(null)}
        >
          ⬅ {t("back_to_list")}
        </Button>

        {offerDetails ? (
          <OfferClient item={offerDetails?.pages[0]?.data} />
        ) : (
          <div className="text-center p-8 text-gray-500">
            لا توجد بيانات لعرضها.
          </div>
        )}
      </div>
    );
  }

  if (isLoading) {
    return <AtayaLoader />;
  }

  return (
    <>
      <div className="space-y-4">
        <div>
          <div className="flex items-center justify-between mb-4 gap-4">
            <div>
              <h2 className="text-xl font-extrabold text-primary">
                {t("title")}
              </h2>
              <p className="text-sm text-slate-500">{t("subtitle")}</p>
            </div>

            <div className="flex flex-wrap items-center gap-2 w-full justify-end">
              <label className="flex flex-col gap-1 w-full min-w-[9rem] max-w-[11rem] sm:max-w-[12rem]">
                <span className="text-xs font-semibold text-slate-600">
                  {t("filter_status_label")}
                </span>
                <select
                  value={status}
                  onChange={(e) => setStatus(e.target.value)}
                  aria-label={t("filter_status_label")}
                  className="w-full px-3 py-2 border rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/40"
                >
                  <option value="">{t("filter_status_all")}</option>
                  <option value="sold">{t("status_sold")}</option>
                  <option value="active">{t("status_active")}</option>
                  <option value="inactive">{t("status_inactive")}</option>
                  <option value="rejected">{t("status_rejected")}</option>
                </select>
              </label>

              <label className="flex flex-col gap-1 w-full min-w-[9rem] max-w-[11rem] sm:max-w-[12rem]">
                <span className="text-xs font-semibold text-slate-600">
                  {t("filter_animal_type_label")}
                </span>
                <select
                  value={animalType}
                  onChange={(e) => setAnimalType(e.target.value)}
                  aria-label={t("filter_animal_type_label")}
                  className="w-full px-3 py-2 border rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/40"
                >
                  <option value="">{t("filter_status_all")}</option>
                  <option value="camel">{t("animal_camel")}</option>
                  <option value="horse">{t("animal_horse")}</option>
                </select>
              </label>

              <div className="w-full max-w-xs min-w-[12rem] flex-1">
                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={t("search_placeholder")}
                  className="w-full px-3 py-2 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/40"
                />
              </div>
            </div>
          </div>

          <>
            {filteredListings.length === 0 ? (
              <div className="text-center p-8">
                <div className="text-gray-400 text-6xl mb-4">🏷️</div>
                <h3 className="text-lg font-bold text-gray-600 mb-2">
                  {t("no_listings")}
                </h3>
                <p className="text-gray-500 text-sm">
                  {t("no_listings_description")}
                </p>
              </div>
            ) : (
              <>
                {/* Cards Grid */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3">
                  {filteredListings.map((l) => {
                    const saleAmount = listingSaleAmount(l);
                    // Badge styling based on status
                    const badgeConfig: Record<
                      string,
                      { dot: string; border: string; label: string }
                    > = {
                      active: {
                        dot: "bg-green-500",
                        border: "border-green-200",
                        label: t("status_active"),
                      },
                      sold: {
                        dot: "bg-slate-500",
                        border: "border-slate-300",
                        label: t("status_sold"),
                      },
                      pending: {
                        dot: "bg-amber-500",
                        border: "border-amber-200",
                        label: t("status_pending"),
                      },
                      inactive: {
                        dot: "bg-slate-400",
                        border: "border-slate-200",
                        label: t("status_inactive"),
                      },
                      rejected: {
                        dot: "bg-red-500",
                        border: "border-red-200",
                        label: t("status_rejected"),
                      },
                    };
                    const badge = badgeConfig[l.status] || {
                      dot: "bg-gray-400",
                      border: "border-gray-200",
                      label: l.status,
                    };

                    return (
                      <article
                        key={l.id}
                        className="bg-white border border-slate-200/60 rounded-2xl shadow-[0_14px_34px_rgba(2,6,23,0.08)] overflow-hidden"
                      >
                        {/* Media */}
                        <div className="relative h-[170px] bg-slate-100 overflow-hidden">
                          <img
                            src={l?.main_image?.url}
                            alt={l?.title}
                            className="w-full h-full object-cover"
                          />

                          {/* Top bar: badge */}
                          <div className="absolute top-2.5 left-2.5 right-2.5 flex items-center justify-between gap-2">
                            <div
                              className={`inline-flex items-center gap-2 h-[30px] px-2.5 rounded-full bg-white ${badge.border} border text-xs font-extrabold shadow-[0_10px_18px_rgba(2,6,23,0.10)] whitespace-nowrap`}
                            >
                              <span
                                className={`w-2 h-2 rounded-full ${badge.dot}`}
                              />
                              {badge.label}
                            </div>
                          </div>

                          {/* Listing ID */}
                          <div className="absolute bottom-2.5 right-2.5 bg-white/90 border border-slate-200 rounded-xl px-2 py-1.5 text-xs font-black shadow-[0_10px_18px_rgba(2,6,23,0.10)] whitespace-nowrap">
                            <span className="text-slate-500 font-bold ml-1.5">
                              {t("card.offer_number_label")}:
                            </span>
                            {l.id.slice(0, 8)}
                          </div>
                        </div>

                        {/* Body */}
                        <div className="p-3">
                          <h3 className="text-lg font-black text-slate-900 leading-tight mb-1 line-clamp-1">
                            {l.title}
                          </h3>

                          {/* Description */}
                          <div className="text-xs text-slate-500 leading-relaxed line-clamp-2 mb-2">
                            {l.description || "—"}
                          </div>

                          {/* Meta row */}
                          <div className="mt-2 flex items-center justify-between gap-2 p-2.5 border border-slate-100 rounded-xl bg-slate-50/50">
                            <div className="flex flex-col gap-0.5 min-w-0">
                              <div className="text-[11px] text-slate-500 font-bold">
                                {t("card.meta_type")}
                              </div>
                              <div className="text-[13px] text-slate-900 font-black truncate">
                                {l.animal_type || "—"}
                              </div>
                            </div>
                            <div className="flex flex-col gap-0.5 min-w-0 text-left">
                              <div className="text-[11px] text-slate-500 font-bold">
                                {t("card.meta_price")}
                              </div>
                              <div className="text-[13px] text-green-600 font-black truncate">
                                {saleAmount !== undefined
                                  ? saleAmount.toLocaleString()
                                  : "—"}{" "}
                                {t("currency")}{" "}
                              </div>
                            </div>
                          </div>

                          {/* Actions */}
                          <div className="mt-2.5 flex flex-wrap gap-2">
                            <button
                              onClick={() => setSelectedListingId(l.id)}
                              className="flex-1 min-w-[90px] h-10 rounded-xl border border-slate-200 bg-white text-slate-900 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-slate-50 active:scale-[0.99] transition-all"
                            >
                              <svg
                                className="w-[18px] h-[18px]"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              >
                                <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z" />
                                <circle cx="12" cy="12" r="3" />
                              </svg>
                              {t("card.actions.view")}
                            </button>

                            <button
                              onClick={() =>
                                router.push(
                                  `/${lang}/dashboard/offers/${l.id}/edit?tab=listings`,
                                )
                              }
                              className="flex-1 min-w-[90px] h-10 rounded-xl border border-slate-200 bg-white text-slate-900 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-slate-50 active:scale-[0.99] transition-all"
                            >
                              <svg
                                className="w-[18px] h-[18px]"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              >
                                <path d="M12 20h9" />
                                <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
                              </svg>
                              {t("card.actions.edit")}
                            </button>

                            <button
                              onClick={async () => {
                                const ok = window.confirm(t("delete_confirm"));
                                if (!ok) return;
                                setDeletingId(l.id);
                                try {
                                  await deleteListing.mutateAsync({ id: l.id });
                                  toast.success(t("delete_success"));
                                } catch (e: any) {
                                  toast.error(
                                    e?.info?.message ||
                                      e?.message ||
                                      t("delete_failed"),
                                  );
                                } finally {
                                  setDeletingId(null);
                                }
                              }}
                              disabled={
                                deletingId !== null && deletingId !== l.id
                              }
                              className="flex-1 min-w-[90px] h-10 rounded-xl border border-red-200 bg-white text-red-600 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-red-50 active:scale-[0.99] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              {deletingId === l.id ? (
                                "..."
                              ) : (
                                <>
                                  <Trash2 className="w-4 h-4" />
                                  {t("card.actions.delete")}
                                </>
                              )}
                            </button>
                          </div>
                        </div>
                      </article>
                    );
                  })}
                </div>

                {hasNextPage && (
                  <div className="flex justify-center mt-4">
                    <Button
                      variant="solid"
                      onPress={() => fetchNextPage()}
                      isLoading={isFetchingNextPage}
                    >
                      {t("load_more")}
                    </Button>
                  </div>
                )}
              </>
            )}
          </>
        </div>
      </div>
    </>
  );
}
