"use client";
import { useEffect, useState, type ReactNode } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import EarningsSummary, {
  type EarningsKpis,
} from "@/components/earnings/EarningsSummary";
import MonthlyCompareChart, {
  type YearlyComparison,
} from "@/components/earnings/MonthlyCompareChart";
import ScooterEarningsTable from "@/components/earnings/ScooterEarningsTable";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { formatMoney } from "@/lib/format";
import type {
  EarningTransactionsData,
  EarningTransactionsSort,
  TransactionsPagination,
} from "@/lib/transactions";

/** One entry in monthly_earnings_chart (the distribution panel). */
export interface MonthlyEarningsEntry {
  month: string;
  label: string; // e.g. "يناير 2026"
  revenue: number;
  profit: number;
  is_current: boolean;
}

/** `data` payload of the provider/earnings endpoint. */
export interface EarningsData {
  currency: string;
  profit_share_percent: number;
  kpis: EarningsKpis;
  yearly_comparison: YearlyComparison;
  monthly_earnings_chart: MonthlyEarningsEntry[];
}

const TX_PER_PAGE = 15;
const MONTHS_OPTIONS = [3, 6, 12] as const;
type MonthsOption = (typeof MONTHS_OPTIONS)[number];

const KPI_SKELETON_KEYS = [
  "earnings-kpi-skeleton-1",
  "earnings-kpi-skeleton-2",
  "earnings-kpi-skeleton-3",
  "earnings-kpi-skeleton-4",
] as const;

const DISTRIBUTION_SKELETON_KEYS = [
  "earnings-distribution-skeleton-1",
  "earnings-distribution-skeleton-2",
  "earnings-distribution-skeleton-3",
  "earnings-distribution-skeleton-4",
  "earnings-distribution-skeleton-5",
  "earnings-distribution-skeleton-6",
] as const;

// ── Skeleton components ─────────────────────────────────────────────────────

function KpisSkeleton() {
  return (
    <div className="grid grid-cols-4 gap-5 mb-6">
      {KPI_SKELETON_KEYS.map((skeletonKey) => (
        <div key={skeletonKey} className="bg-[#1E2128] rounded-2xl p-5 animate-pulse">
          <div className="w-10 h-10 bg-white/5 rounded-xl mb-4" />
          <div className="h-7 w-28 bg-white/10 rounded mt-2" />
          <div className="h-3 w-20 bg-white/5 rounded mt-2" />
          <div className="h-3 w-16 bg-white/5 rounded mt-2" />
        </div>
      ))}
    </div>
  );
}

function ChartSkeleton() {
  return (
    <div className="bg-[#1E2128] rounded-2xl p-6 animate-pulse">
      <div className="flex items-center justify-between mb-6">
        <div className="h-3 w-20 bg-white/5 rounded" />
        <div className="h-4 w-36 bg-white/10 rounded" />
      </div>
      <div className="h-[260px] bg-white/5 rounded-xl" />
    </div>
  );
}

function DistributionSkeleton() {
  return (
    <div className="bg-[#1E2128] rounded-2xl p-6 animate-pulse flex flex-col gap-4">
      <div className="h-4 w-24 bg-white/10 rounded self-end" />
      {DISTRIBUTION_SKELETON_KEYS.map((skeletonKey) => (
        <div key={skeletonKey}>
          <div className="flex items-center justify-between mb-1.5">
            <div className="h-3 w-16 bg-white/10 rounded" />
            <div className="h-3 w-12 bg-white/5 rounded" />
          </div>
          <div className="h-2 bg-white/5 rounded-full" />
        </div>
      ))}
      <div className="mt-2 pt-4 border-t border-white/5 flex items-center justify-between">
        <div className="h-6 w-24 bg-white/10 rounded" />
        <div className="h-3 w-32 bg-white/5 rounded" />
      </div>
    </div>
  );
}

function renderKpisSection({
  earningsLoading,
  earningsError,
  earnings,
  currency,
}: {
  earningsLoading: boolean;
  earningsError: string;
  earnings: EarningsData | null;
  currency: string;
}): ReactNode {
  if (earningsLoading) {
    return <KpisSkeleton />;
  }

  if (earningsError) {
    return (
      <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-center mb-6">
        <i className="ri-error-warning-line text-red-400 text-2xl mb-2 block" />
        <p className="text-red-400 text-sm">{earningsError}</p>
      </div>
    );
  }

  if (earnings) {
    return <EarningsSummary kpis={earnings.kpis} currency={currency} />;
  }

  return null;
}

function renderCompareChartSection({
  earningsLoading,
  earnings,
}: {
  earningsLoading: boolean;
  earnings: EarningsData | null;
}): ReactNode {
  if (earningsLoading) {
    return <ChartSkeleton />;
  }

  if (earnings) {
    return <MonthlyCompareChart data={earnings.yearly_comparison} />;
  }

  return null;
}

function renderDistributionContent({
  earningsLoading,
  chart,
  maxProfit,
  totalProfit,
  currency,
  months,
}: {
  earningsLoading: boolean;
  chart: MonthlyEarningsEntry[];
  maxProfit: number;
  totalProfit: number;
  currency: string;
  months: MonthsOption;
}): ReactNode {
  if (earningsLoading) {
    return <DistributionSkeleton />;
  }

  if (chart.length === 0) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center py-8">
        <i className="ri-bar-chart-line text-gray-600 text-3xl mb-2" />
        <p className="text-gray-500 text-sm">لا توجد بيانات</p>
      </div>
    );
  }

  return (
    <>
      {chart.map((m) => {
        const pct = Math.round((m.profit / maxProfit) * 100);
        return (
          <div key={m.month}>
            <div className="flex items-center justify-between mb-1.5">
              <span
                className={`text-xs font-semibold ${m.is_current ? "text-[#FCD704]" : "text-white/70"}`}
              >
                {formatMoney(m.profit, currency)}
                {m.is_current && (
                  <span className="text-[10px] text-[#FCD704]/70 mr-1">
                    الشهر الحالي
                  </span>
                )}
              </span>
              <span className="text-gray-400 text-xs">{m.label}</span>
            </div>
            <div className="h-2 bg-white/8 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${m.is_current ? "bg-[#FCD704]" : "bg-[#FCD704]/50"}`}
                style={{
                  width: `${pct}%`,
                  opacity: 0.4 + pct / 200,
                }}
              />
            </div>
          </div>
        );
      })}
      <div className="mt-2 pt-4 border-t border-white/5 flex items-center justify-between">
        <span className="text-[#FCD704] font-black text-xl">
          {formatMoney(totalProfit, currency)}
        </span>
        <span className="text-gray-400 text-sm">إجمالي {months} أشهر</span>
      </div>
    </>
  );
}

// ── Main page ───────────────────────────────────────────────────────────────

export default function EarningsPage() {
  // ── Earnings fetch state ──────────────────────────────────────────────────
  const [months, setMonths] = useState<MonthsOption>(6);
  const [earnings, setEarnings] = useState<EarningsData | null>(null);
  const [earningsLoading, setEarningsLoading] = useState(true);
  const [earningsError, setEarningsError] = useState("");

  // ── Transactions fetch state (reuses provider/transactions, same as home) ─
  const [txPage, setTxPage] = useState(1);
  const [txSort, setTxSort] =
    useState<EarningTransactionsSort>("monthly_revenue");
  const [txData, setTxData] = useState<EarningTransactionsData | null>(null);
  const [txLoading, setTxLoading] = useState(true);
  const [txError, setTxError] = useState("");

  // ── Fetch: provider/earnings (refetches when months changes) ─────────────
  useEffect(() => {
    let active = true;
    setEarningsLoading(true);
    setEarningsError("");
    apiFetch<EarningsData>(`/provider/earnings?months=${months}`, {
      method: "GET",
      successCase: (res) => {
        if (active && res.data) setEarnings(res.data);
      },
      errorCase: (res) => {
        if (active)
          setEarningsError(
            formatApiMsg(res.msg) ||
              "تعذّر تحميل بيانات الأرباح، حاول مرة أخرى",
          );
      },
    }).finally(() => {
      if (active) setEarningsLoading(false);
    });
    return () => {
      active = false;
    };
  }, [months]);

  // ── Fetch: provider/earning-transactions (refetches when page/sort changes) ─
  useEffect(() => {
    let active = true;
    setTxLoading(true);
    setTxError("");
    const url = `/provider/earning-transactions?page=${txPage}&per_page=${TX_PER_PAGE}&sort=${txSort}`;
    apiFetch<EarningTransactionsData>(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, txSort]);

  const handleTxSortChange = (sort: EarningTransactionsSort) => {
    setTxSort(sort);
    setTxPage(1);
  };

  // ── Distribution panel data ───────────────────────────────────────────────
  const chart = earnings?.monthly_earnings_chart ?? [];
  // Max profit value for relative bar widths.
  const maxProfit = Math.max(1, ...chart.map((m) => m.profit));
  const totalProfit = chart.reduce((s, m) => s + m.profit, 0);
  const currency = earnings?.currency ?? "SAR";

  // ── Pagination meta (passed down to table) ────────────────────────────────
  const txPagination: TransactionsPagination | null =
    txData?.pagination ?? null;

  return (
    <DashboardLayout
      title="الأرباح"
      subtitle="تحليل شامل لأرباحك ومقارنة الأداء"
    >
      {/* ── Months selector ─────────────────────────────────────────────── */}
      <div className="flex justify-start mb-5">
        <div className="flex items-center gap-2 bg-[#1E2128] p-1 rounded-xl">
          {MONTHS_OPTIONS.map((m) => (
            <button
              key={m}
              onClick={() => {
                setMonths(m);
                setTxPage(1); // reset table page on range change
              }}
              disabled={earningsLoading}
              className={`px-4 py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all disabled:cursor-not-allowed ${
                months === m
                  ? "bg-[#FCD704] text-[#13151A]"
                  : "text-gray-400 hover:text-white"
              }`}
            >
              {m} أشهر
            </button>
          ))}
        </div>
      </div>

      {/* ── KPI cards ───────────────────────────────────────────────────── */}
      {renderKpisSection({
        earningsLoading,
        earningsError,
        earnings,
        currency,
      })}

      {/* ── Charts row: compare chart (col-span-2) + distribution (col-span-1) */}
      <div className="grid grid-cols-3 gap-6 mb-6">
        <div className="col-span-2">
          {renderCompareChartSection({ earningsLoading, earnings })}
        </div>

        {/* Distribution panel — monthly_earnings_chart → profit bars */}
        <div className="bg-[#1E2128] rounded-2xl p-6 flex flex-col gap-4">
          <h3 className="text-white font-bold text-right">توزيع الأرباح</h3>
          {renderDistributionContent({
            earningsLoading,
            chart,
            maxProfit,
            totalProfit,
            currency,
            months,
          })}
        </div>
      </div>

      {/* ── ScooterEarningsTable — wired to provider/transactions ─────────── */}
      {txError ? (
        <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-8 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>
      ) : (
        <ScooterEarningsTable
          rows={txData?.vehicles ?? []}
          currency={txData?.currency ?? currency}
          pagination={txPagination}
          loading={txLoading}
          page={txPage}
          sort={txSort}
          totalMonthlyShare={txData?.total_monthly_share}
          onPageChange={setTxPage}
          onSortChange={handleTxSortChange}
        />
      )}
    </DashboardLayout>
  );
}
