"use client";
import { useEffect, useState, type ReactNode } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import SummaryCards, { type HomeCards } from "@/components/home/SummaryCards";
import ProfitBanner, { type ProfitShare } from "@/components/home/ProfitBanner";
import EarningsChart, { type ChartBar } from "@/components/home/EarningsChart";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { formatMoney } from "@/lib/format";
import type { TransactionsData } from "@/lib/transactions";
export type { TransactionsData, TransactionRow, TransactionsPagination } from "@/lib/transactions";

/** `data` payload of the provider/home endpoint. */
export interface HomeData {
  currency: string;
  cards: HomeCards;
  profit_share: ProfitShare;
  monthly_profits_chart: {
    range_months: number;
    bars: ChartBar[];
  };
}

const TX_PER_PAGE = 15;

const HOME_CARD_SKELETON_KEYS = [
  "home-card-skeleton-1",
  "home-card-skeleton-2",
  "home-card-skeleton-3",
  "home-card-skeleton-4",
] as const;

const TRANSACTION_SKELETON_KEYS = [
  "home-transaction-skeleton-1",
  "home-transaction-skeleton-2",
  "home-transaction-skeleton-3",
  "home-transaction-skeleton-4",
  "home-transaction-skeleton-5",
] as const;

// Loading skeleton — cards + chart + banner, in the app's palette/radii.
function HomeSkeleton() {
  return (
    <>
      <div className="grid grid-cols-4 gap-5">
        {HOME_CARD_SKELETON_KEYS.map((skeletonKey) => (
          <div key={skeletonKey} className="bg-[#1E2128] rounded-2xl p-5 animate-pulse">
            <div className="flex items-center justify-between mb-4">
              <div className="h-3 w-20 bg-white/5 rounded" />
              <div className="w-10 h-10 bg-white/5 rounded-xl" />
            </div>
            <div className="h-7 w-24 bg-white/10 rounded mt-2" />
            <div className="h-3 w-16 bg-white/5 rounded mt-2" />
          </div>
        ))}
      </div>
      <div className="grid grid-cols-3 gap-6 mt-6">
        <div className="col-span-2 bg-[#1E2128] rounded-2xl p-6 animate-pulse">
          <div className="flex items-center justify-between mb-6">
            <div className="h-3 w-16 bg-white/5 rounded" />
            <div className="h-4 w-24 bg-white/10 rounded" />
          </div>
          <div className="h-[240px] bg-white/5 rounded-xl" />
        </div>
        <div className="bg-[#1E2128] rounded-2xl p-6 animate-pulse min-h-[300px] flex flex-col justify-between">
          <div className="h-4 w-32 bg-white/10 rounded" />
          <div className="h-16 w-24 bg-white/10 rounded mx-auto my-8" />
          <div className="h-12 bg-white/5 rounded-xl" />
        </div>
      </div>
    </>
  );
}

/** Skeleton rows shown while the transactions table is loading. */
function TransactionsSkeleton() {
  return (
    <>
      {TRANSACTION_SKELETON_KEYS.map((skeletonKey) => (
        <tr key={skeletonKey} className="border-b border-white/5 last:border-0">
          <td className="py-4 px-6 text-left">
            <div className="h-4 w-20 bg-white/10 rounded animate-pulse" />
          </td>
          <td className="py-4 px-6 text-center">
            <div className="h-3 w-24 bg-white/5 rounded animate-pulse mx-auto" />
          </td>
          <td className="py-4 px-6 text-center">
            <div className="h-3 w-12 bg-white/5 rounded animate-pulse mx-auto" />
          </td>
          <td className="py-4 px-6 text-center">
            <div className="h-3 w-16 bg-white/5 rounded animate-pulse mx-auto" />
          </td>
          <td className="py-4 px-6 text-right">
            <div className="flex items-center gap-2 justify-end">
              <div className="h-4 w-20 bg-white/10 rounded animate-pulse" />
              <div className="w-8 h-8 bg-white/5 rounded-lg animate-pulse" />
            </div>
          </td>
        </tr>
      ))}
    </>
  );
}

function renderHomeContent({
  loading,
  error,
  home,
}: {
  loading: boolean;
  error: string;
  home: HomeData | null;
}): ReactNode {
  if (loading) {
    return <HomeSkeleton />;
  }

  if (error) {
    return (
      <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-center">
        <p className="text-red-400 text-sm">{error}</p>
      </div>
    );
  }

  if (home) {
    return (
      <>
        <SummaryCards cards={home.cards} currency={home.currency} />
        <div className="grid grid-cols-3 gap-6 mt-6">
          <div className="col-span-2">
            <EarningsChart
              bars={home.monthly_profits_chart.bars}
              currency={home.currency}
              rangeMonths={home.monthly_profits_chart.range_months}
            />
          </div>
          <div className="flex flex-col gap-6">
            <ProfitBanner
              profitShare={home.profit_share}
              currency={home.currency}
            />
          </div>
        </div>
      </>
    );
  }

  return (
    <div className="bg-[#1E2128] rounded-2xl p-10 text-center">
      <p className="text-gray-400 text-sm">لا توجد بيانات لعرضها</p>
    </div>
  );
}

function renderTransactionsRows({
  txLoading,
  txData,
}: {
  txLoading: boolean;
  txData: TransactionsData | null;
}): ReactNode {
  if (txLoading) {
    return <TransactionsSkeleton />;
  }

  if (!txData || txData.transactions.length === 0) {
    return (
      <tr>
        <td colSpan={5} 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 txData.transactions.map((tx) => (
    <tr
      key={`${tx.scooter_code}-${tx.last_ride_at}`}
      className="border-b border-white/5 last:border-0 hover:bg-white/2 transition-colors"
    >
      <td className="py-4 px-6">
        <span className="text-[#FCD704] font-bold text-sm block">
          +{formatMoney(tx.your_share, txData.currency)}
        </span>
        <span className="text-gray-500 text-xs block mt-0.5">
          إيراد: {formatMoney(tx.revenue, txData.currency)}
        </span>
      </td>
      <td className="py-4 px-6 text-gray-400 text-sm" title={tx.last_ride_at}>
        {tx.relative_time}
      </td>
      <td className="py-4 px-6 text-gray-300 text-sm">{tx.rides_count} رحلة</td>
      <td className="py-4 px-6 text-gray-300 text-sm">{tx.area}</td>
      <td className="py-4 px-6 text-start">
        <div className="flex items-center gap-2 justify-end">
          <span className="text-white font-semibold text-sm">{tx.scooter_code}</span>
          <div className="w-8 h-8 bg-[#FCD704]/15 rounded-lg flex items-center justify-center">
            <i className="ri-e-bike-line text-[#FCD704] text-sm" />
          </div>
        </div>
      </td>
    </tr>
  ));
}

export default function HomePage() {
  const [home, setHome] = useState<HomeData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  // Transactions — separate state from the home cards/chart fetch.
  const [txPage, setTxPage] = useState(1);
  const [txData, setTxData] = useState<TransactionsData | null>(null);
  const [txLoading, setTxLoading] = useState(true);
  const [txError, setTxError] = useState("");

  // ── Home cards / chart / banner ─────────────────────────────────────────
  useEffect(() => {
    let active = true;
    setLoading(true);
    setError("");
    // Client-side fetch (static export). Branch on body.key, never HTTP status.
    apiFetch<HomeData>("/provider/home", {
      method: "GET",
      successCase: (res) => {
        if (active && res.data) setHome(res.data);
      },
      errorCase: (res) => {
        if (active)
          setError(
            formatApiMsg(res.msg) || "تعذّر تحميل البيانات، حاول مرة أخرى",
          );
      },
    }).finally(() => {
      if (active) setLoading(false);
    });
    return () => {
      active = false;
    };
  }, []);

  // ── Transactions table (own fetch, refetches on page change) ─────────────
  useEffect(() => {
    let active = true;
    setTxLoading(true);
    setTxError("");
    // Query params appended to the URL string — apiFetch has no params field.
    const url = `/provider/transactions?page=${txPage}&per_page=${TX_PER_PAGE}`;
    apiFetch<TransactionsData>(url, {
      method: "GET",
      successCase: (res) => {
        if (active && res.data) setTxData(res.data);
      },
      errorCase: (res) => {
        if (active)
          setTxError(
            formatApiMsg(res.msg) || "تعذّر تحميل المعاملات، حاول مرة أخرى",
          );
      },
    }).finally(() => {
      if (active) setTxLoading(false);
    });
    return () => {
      active = false;
    };
  }, [txPage]);

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

  return (
    <DashboardLayout
      title="لوحة التحكم"
      subtitle="مرحباً بك في لوحة مستثمر BEEPBEEP"
    >
      {renderHomeContent({ loading, error, home })}

      {/* Recent transactions — wired to provider/transactions, own state. */}
      <div className="mt-6 bg-[#1E2128] rounded-2xl overflow-hidden">
        <div className="flex items-center justify-between px-6 py-4 border-b border-white/5">
          <button className="text-[#FCD704] text-sm cursor-pointer">
            عرض الكل
          </button>
          <h3 className="text-white font-bold">آخر المعاملات</h3>
        </div>

        {txError ? (
          /* ── Error state ─────────────────────────────────────────────────── */
          <div className="px-6 py-10 text-center">
            <i className="ri-error-warning-line text-red-400 text-3xl mb-3 block" />
            <p className="text-red-400 text-sm">{txError}</p>
          </div>
        ) : (
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/5">
                {/*
                  Column mapping (real → mock → column header):
                  • your_share  → amount  → المبلغ   (investor's share; revenue shown as sub-text)
                  • relative_time → time  → الوقت    (server-provided, rendered directly)
                  • rides_count → trips  → الرحلات
                  • area        → area   → المنطقة
                  • scooter_code → id    → المركبة
                */}
                <th className="text-gray-400 text-xs font-medium py-3 px-6 text-start">
                  المبلغ
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6 text-start">
                  الوقت
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6 text-start">
                  الرحلات
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6 text-start">
                  المنطقة
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6 text-start">
                  المركبة
                </th>
              </tr>
            </thead>
            <tbody>
              {renderTransactionsRows({ txLoading, txData })}
            </tbody>
          </table>
        )}

        {/* ── Pagination — only shown when last_page > 1 ─────────────────── */}
        {showPagination && (
          <div className="flex items-center justify-between px-6 py-4 border-t border-white/5">
            {/* Total info (RTL: appears on the left visually) */}
            <p className="text-gray-500 text-xs">{pagination.total} معاملة</p>

            {/* Page controls */}
            <div className="flex items-center gap-1">
              {/* Next page (RTL: rightmost = next for Arabic readers) */}
              <button
                onClick={() => setTxPage((p) => Math.max(1, p - 1))}
                disabled={pagination.current_page <= 1 || txLoading}
                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>

              {/* Page number pills */}
              {Array.from(
                { length: pagination.last_page },
                (_, i) => i + 1,
              ).map((p) => (
                <button
                  key={p}
                  onClick={() => setTxPage(p)}
                  disabled={txLoading}
                  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>
              ))}

              {/* Prev page (RTL: leftmost = prev for Arabic readers) */}
              <button
                onClick={() =>
                  setTxPage((p) => Math.min(pagination.last_page, p + 1))
                }
                disabled={
                  pagination.current_page >= pagination.last_page || txLoading
                }
                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>
    </DashboardLayout>
  );
}
