"use client";
import { formatMoney } from "@/lib/format";
import {
  EARNING_TRANSACTIONS_SORT_OPTIONS,
  type EarningTransactionsSort,
  type EarningVehicle,
  type TransactionsPagination,
} from "@/lib/transactions";

export type { EarningTransactionsSort };

interface Props {
  rows: EarningVehicle[];
  currency: string;
  pagination: TransactionsPagination | null;
  loading: boolean;
  page: number;
  sort: EarningTransactionsSort;
  totalMonthlyShare?: number | null;
  onPageChange: (p: number) => void;
  onSortChange: (sort: EarningTransactionsSort) => void;
}

const TABLE_SKELETON_KEYS = [
  "earnings-table-skeleton-1",
  "earnings-table-skeleton-2",
  "earnings-table-skeleton-3",
  "earnings-table-skeleton-4",
  "earnings-table-skeleton-5",
] as const;

/** Skeleton rows for the table loading state. */
function TableSkeleton() {
  return (
    <>
      {TABLE_SKELETON_KEYS.map((skeletonKey) => (
        <tr key={skeletonKey} className="border-b border-white/5 last:border-0">
          <td className="py-4 px-5">
            <div className="h-4 w-16 bg-white/10 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="h-3 w-14 bg-white/5 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="h-3 w-20 bg-white/5 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="h-3 w-10 bg-white/5 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="h-3 w-16 bg-white/5 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="h-3 w-20 bg-white/5 rounded animate-pulse" />
          </td>
          <td className="py-4 px-5">
            <div className="flex items-center gap-2 justify-end">
              <div className="h-4 w-16 bg-white/10 rounded animate-pulse" />
              <div className="w-9 h-9 bg-white/5 rounded-xl animate-pulse" />
            </div>
          </td>
        </tr>
      ))}
    </>
  );
}

/** Status styles mapping. */
function getStatusStyles(status: string) {
  switch (status) {
    case "active":
      return {
        wrapper: "bg-[#FCD704]/10 text-[#FCD704]",
        dot: "bg-[#FCD704]",
      };
    case "maintenance":
      return {
        wrapper: "bg-orange-400/10 text-orange-400",
        dot: "bg-orange-400",
      };
    default:
      return {
        wrapper: "bg-gray-400/10 text-gray-400",
        dot: "bg-gray-400",
      };
  }
}

function renderTableBody({
  loading,
  rows,
  currency,
}: {
  loading: boolean;
  rows: EarningVehicle[];
  currency: string;
}) {
  if (loading) {
    return <TableSkeleton />;
  }

  if (rows.length === 0) {
    return (
      <tr>
        <td colSpan={7} className="py-12 text-center">
          <i className="ri-file-list-3-line text-gray-600 text-4xl mb-3 block" />
          <p className="text-gray-500 text-sm">لا توجد بيانات لعرضها</p>
        </td>
      </tr>
    );
  }

  return rows.map((v) => (
    <tr
      key={v.scooter_id}
      className="border-b border-white/5 last:border-0 hover:bg-white/2 transition-colors"
    >
      <td className="py-4 px-5 text-right">
        <span className="text-[#FCD704] font-bold text-sm">
          {v.monthly_share > 0 ? formatMoney(v.monthly_share, currency) : "—"}
        </span>
      </td>
      <td className="py-4 px-5 text-right">
        <span className="text-white font-semibold text-sm">
          {v.monthly_revenue > 0 ? formatMoney(v.monthly_revenue, currency) : "—"}
        </span>
      </td>
      <td className="py-4 px-5 text-right">
        <span className="text-gray-300 text-sm">
          {v.daily_revenue > 0 ? formatMoney(v.daily_revenue, currency) : "—"}
        </span>
      </td>
      <td className="py-4 px-5 text-right">
        <span className="text-gray-300 text-sm">
          {v.rides_today > 0 ? v.rides_today : "—"}
        </span>
      </td>
      <td className="py-4 px-5 text-right">
        <span className="text-gray-400 text-sm">{v.area}</span>
      </td>
      <td className="py-4 px-5 text-right">
        <div className="flex items-center">
          <span
            className={`inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold ${getStatusStyles(v.status).wrapper}`}
          >
            <span
              className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${getStatusStyles(v.status).dot}`}
            />
            {v.status_label}
          </span>
        </div>
      </td>
      <td className="py-4 px-5 text-right">
        <div className="flex items-center gap-3 justify-end">
          <div className="flex flex-col items-end">
            <p className="text-white font-semibold text-sm">{v.code}</p>
            <div className="flex items-center gap-2 mt-1">
              <span className="text-gray-500 text-[10px] leading-none">
                {v.utilization_percent}%
              </span>
              <div className="h-1 w-12 bg-white/10 rounded-full overflow-hidden flex justify-end">
                <div
                  className="h-full bg-[#FCD704] rounded-full"
                  style={{ width: `${v.utilization_percent}%` }}
                />
              </div>
            </div>
          </div>
          <div className="w-10 h-10 bg-[#FCD704]/10 rounded-xl flex items-center justify-center flex-shrink-0 border border-[#FCD704]/20">
            <i className="ri-e-bike-2-fill text-[#FCD704] text-lg" />
          </div>
        </div>
      </td>
    </tr>
  ));
}

export default function ScooterEarningsTable({
  rows,
  currency,
  pagination,
  loading,
  page,
  sort,
  totalMonthlyShare,
  onPageChange,
  onSortChange,
}: Readonly<Props>) {
  const pageTotal =
    totalMonthlyShare ??
    rows.reduce((sum, row) => sum + row.monthly_share, 0);

  const showPagination = pagination && pagination.last_page > 1;

  return (
    <div className="bg-[#1E2128] rounded-2xl overflow-hidden">
      {/* Header + sort controls */}
      <div className="flex items-center justify-between px-6 py-4 border-b border-white/5">
        <div className="flex items-center gap-2">
          {EARNING_TRANSACTIONS_SORT_OPTIONS.map(({ value, label }) => (
            <button
              key={value}
              type="button"
              onClick={() => onSortChange(value)}
              disabled={loading}
              className={`px-3 py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all disabled:cursor-not-allowed disabled:opacity-60 ${sort === value ? "bg-[#FCD704] text-[#13151A]" : "bg-[#13151A] text-gray-400 hover:text-white"}`}
            >
              {label}
            </button>
          ))}
        </div>
        <h3 className="text-white font-bold">أرباح كل مركبة</h3>
      </div>

      <table className="w-full">
        <thead>
          <tr className="border-b border-white/5">
            {[
              "نصيبك",
              "الإيراد الشهري",
              "الإيراد اليومي",
              "الرحلات اليوم",
              "المنطقة",
              "الحالة",
              "المركبة",
            ].map((h) => (
              <th
                key={h}
                className="text-gray-400 text-xs font-medium py-3 px-5 text-right"
              >
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>{renderTableBody({ loading, rows, currency })}</tbody>
      </table>

      {/* Footer: page total */}
      {!loading && rows.length > 0 && (
        <div className="flex items-center justify-between px-6 py-4 border-t border-white/5 bg-[#13151A]/50">
          <span className="text-[#FCD704] font-black text-lg">
            {formatMoney(pageTotal, currency)}
          </span>
          <div className="flex items-center gap-3">
            <span className="text-gray-400 text-sm">
              إجمالي نصيبك هذا الشهر
            </span>
            <i className="ri-coins-line text-[#FCD704] text-xl" />
          </div>
        </div>
      )}

      {/* Pagination — only when last_page > 1 */}
      {showPagination && (
        <div className="flex items-center justify-between px-6 py-4 border-t border-white/5">
          <p className="text-gray-500 text-xs">{pagination.total} مركبة</p>
          <div className="flex items-center gap-1">
            <button
              type="button"
              onClick={() => onPageChange(Math.max(1, page - 1))}
              disabled={pagination.current_page <= 1 || loading}
              className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:bg-white/5 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              aria-label="الصفحة السابقة"
            >
              <i className="ri-arrow-right-s-line text-lg" />
            </button>
            {Array.from({ length: pagination.last_page }, (_, i) => i + 1).map(
              (p) => (
                <button
                  key={p}
                  type="button"
                  onClick={() => onPageChange(p)}
                  disabled={loading}
                  className={`w-8 h-8 flex items-center justify-center rounded-lg text-sm font-medium transition-colors disabled:cursor-not-allowed ${
                    p === pagination.current_page
                      ? "bg-[#FCD704] text-[#13151A]"
                      : "text-gray-400 hover:bg-white/5 hover:text-white"
                  }`}
                >
                  {p}
                </button>
              ),
            )}
            <button
              type="button"
              onClick={() =>
                onPageChange(Math.min(pagination.last_page, page + 1))
              }
              disabled={
                pagination.current_page >= pagination.last_page || loading
              }
              className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:bg-white/5 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              aria-label="الصفحة التالية"
            >
              <i className="ri-arrow-left-s-line text-lg" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
