"use client";

import { AnimatePresence, motion } from "framer-motion";
import {
  Button,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
} from "@heroui/react";
import { Eye, MoreVertical, Pencil, Trash2, XCircle } from "lucide-react";
import type {
  LiveRoom,
  SingleAuctionItem,
  StatusMeta,
  TranslationFn,
} from "@/components/annaulMazad/live-rooms-table/types";
import { buildAnimalDisplayName } from "@/components/annaulMazad/live-rooms-table/utils";

interface RoomItemsPanelProps {
  selectedRoomId: string | null;
  loadingRoom: boolean;
  roomItems: SingleAuctionItem[];
  currentSelectedRoom: LiveRoom | null;
  hideActions: boolean;
  isRtl: boolean;
  tStatus: TranslationFn;
  resolveRoomTitle: (room: LiveRoom) => string;
  resolveBackendStatus: (raw: string | null | undefined) => StatusMeta;
  statusClass: (state: string | null | undefined) => string;
  onViewItem: (item: SingleAuctionItem) => void;
  onEditItem: (item: SingleAuctionItem) => void;
  onWithdrawItem: (item: SingleAuctionItem) => void;
  onDeleteItem: (item: SingleAuctionItem) => void;
}

export default function RoomItemsPanel({
  selectedRoomId,
  loadingRoom,
  roomItems,
  currentSelectedRoom,
  hideActions,
  isRtl,
  tStatus,
  resolveRoomTitle,
  resolveBackendStatus,
  statusClass,
  onViewItem,
  onEditItem,
  onWithdrawItem,
  onDeleteItem,
}: RoomItemsPanelProps) {
  return (
    <AnimatePresence>
      {selectedRoomId ? (
        <motion.div
          key={`room-items-${selectedRoomId}`}
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 12 }}
          transition={{ duration: 0.2 }}
          className="overflow-hidden rounded-[28px] border border-[#e3ece5] bg-white shadow-[0_30px_70px_-38px_rgba(15,81,50,0.45)]"
        >
          <AnimatePresence mode="wait">
            {loadingRoom ? (
              <motion.div
                key="room-items-loading"
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                transition={{ duration: 0.2 }}
                className="px-5 py-10 text-center text-sm text-slate-500"
              >
                {tStatus("loading")}
              </motion.div>
            ) : (
              <motion.div
                key={`room-items-content-${selectedRoomId}`}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                transition={{ duration: 0.2 }}
              >
                <header className="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 md:flex-row md:items-center md:justify-between">
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">
                      {tStatus("room_content_title")}
                    </div>
                    <div className="mt-1 text-base font-black text-slate-900">
                      {currentSelectedRoom
                        ? resolveRoomTitle(currentSelectedRoom)
                        : tStatus("room_content_title")}
                    </div>
                  </div>

                  <div className="flex flex-wrap items-center gap-2">
                    {currentSelectedRoom?.day_order != null ? (
                      <span className="inline-flex rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-bold text-slate-700">
                        {isRtl
                          ? `الغرفة ${currentSelectedRoom.day_order}`
                          : `Room ${currentSelectedRoom.day_order}`}
                      </span>
                    ) : null}
                    <span className="inline-flex rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-xs font-bold text-emerald-800">
                      {isRtl
                        ? `${roomItems.length} عنصر`
                        : `${roomItems.length} items`}
                    </span>
                  </div>
                </header>

                {roomItems.length === 0 ? (
                  <div className="py-10 text-center text-sm text-slate-500">
                    {tStatus("room_items_empty")}
                  </div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="min-w-[820px] w-full text-sm">
                      <thead>
                        <tr className="bg-slate-50 text-xs text-slate-500">
                          <th className="w-28 border-b border-slate-100 p-4 text-center font-semibold">
                            {tStatus("room_items_table.th_number")}
                          </th>
                          <th className="w-[420px] border-b border-slate-100 p-4 text-start font-semibold">
                            {tStatus("room_items_table.th_animal")}
                          </th>
                          <th className="w-28 border-b border-slate-100 p-4 text-center font-semibold">
                            {tStatus("th_status")}
                          </th>
                          <th className="w-32 border-b border-slate-100 p-4 text-center font-semibold">
                            {tStatus("th_view_details")}
                          </th>
                          {!hideActions ? (
                            <th className="w-28 border-b border-slate-100 p-4 text-center font-semibold">
                              {isRtl ? "الإجراءات" : "Actions"}
                            </th>
                          ) : null}
                        </tr>
                      </thead>

                      <tbody className="divide-y divide-slate-100">
                        {roomItems.map((item, index) => {
                          const imageUrl =
                            item.main_image?.url ||
                            item.media_files?.main_image?.url ||
                            item.main_image_url ||
                            "/logo.png";
                          const fallbackTitle =
                            item.title ||
                            item.horse_name ||
                            tStatus("item_fallback", {
                              id: String(item.id),
                            });
                          const title = buildAnimalDisplayName(
                            item,
                            fallbackTitle,
                          );
                          const itemStatus = resolveBackendStatus(item.status);

                          return (
                            <tr
                              key={String(item.id)}
                              className="transition-colors hover:bg-slate-50"
                            >
                              <td className="p-4 text-center font-black text-slate-900">
                                {index + 1}
                              </td>
                              <td className="p-4 text-start">
                                <div className="flex items-center gap-3">
                                  <div className="h-12 w-14 shrink-0 overflow-hidden rounded-xl bg-slate-100">
                                    <img
                                      src={imageUrl}
                                      alt={title}
                                      className="h-full w-full object-cover"
                                    />
                                  </div>
                                  <div className="min-w-0">
                                    <div className="truncate font-bold text-slate-800">
                                      {title}
                                    </div>
                                  </div>
                                </div>
                              </td>
                              <td className="p-4 text-center">
                                <span
                                  className={`inline-flex items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-bold ${statusClass(
                                    itemStatus.statusKey || item.status,
                                  )}`}
                                >
                                  {itemStatus.statusLabel || item.status || "—"}
                                </span>
                              </td>
                              <td className="p-4 text-center">
                                <button
                                  type="button"
                                  className="rounded-full border cursor-pointer border-emerald-100 bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100"
                                  onClick={() => onViewItem(item)}
                                >
                                  {tStatus("button_view")}
                                </button>
                              </td>
                              {!hideActions ? (
                                <td className="p-4 text-center">
                                  <Dropdown>
                                    <DropdownTrigger>
                                      <Button
                                        isIconOnly
                                        size="sm"
                                        variant="light"
                                        className="text-slate-500 hover:text-slate-700"
                                      >
                                        <MoreVertical size={16} />
                                      </Button>
                                    </DropdownTrigger>
                                    <DropdownMenu aria-label="Actions">
                                      <DropdownItem
                                        key="view"
                                        startContent={<Eye size={14} />}
                                        onPress={() => onViewItem(item)}
                                      >
                                        {isRtl ? "مشاهدة" : "View"}
                                      </DropdownItem>
                                      <DropdownItem
                                        key="edit"
                                        startContent={<Pencil size={14} />}
                                        onPress={() => onEditItem(item)}
                                      >
                                        {isRtl ? "تعديل" : "Edit"}
                                      </DropdownItem>
                                      <DropdownItem
                                        key="withdraw"
                                        className="text-amber-600"
                                        startContent={<XCircle size={14} />}
                                        onPress={() => onWithdrawItem(item)}
                                      >
                                        {isRtl ? "سحب" : "Withdraw"}
                                      </DropdownItem>
                                      <DropdownItem
                                        key="delete"
                                        className="text-red-600"
                                        startContent={<Trash2 size={14} />}
                                        onPress={() => onDeleteItem(item)}
                                      >
                                        {isRtl ? "حذف" : "Delete"}
                                      </DropdownItem>
                                    </DropdownMenu>
                                  </Dropdown>
                                </td>
                              ) : null}
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>
      ) : null}
    </AnimatePresence>
  );
}
