"use client";
import { useEffect, useState, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import Link from "next/link";
import DashboardLayout from "@/components/DashboardLayout";
import { formatMoney } from "@/lib/format";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { formatProfitRate } from "@/lib/profitRate";
import type { Settlement } from "@/components/settlements/SettlementsTable";
import type { SettleableRide } from "@/components/settlements/SettleableRidesTable";

interface SettlementDetails extends Settlement {
  currency: string;
  rides: SettleableRide[];
}

function getSettlementStatusClass(status: Settlement["status"]): string {
  if (status === "pending") {
    return "text-blue-400 bg-blue-400/15";
  }
  if (status === "accepted") {
    return "text-green-400 bg-green-400/15";
  }
  if (status === "rejected") {
    return "text-red-400 bg-red-400/15";
  }
  return "text-gray-400 bg-white/5";
}

function SettlementDetailsContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const id = searchParams.get("id");

  const [data, setData] = useState<SettlementDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!id) {
      setError("لم يتم توفير رقم التسوية");
      setLoading(false);
      return;
    }

    let active = true;
    setLoading(true);
    setError("");

    apiFetch<SettlementDetails>(`/provider/settlements/${id}`, {
      method: "GET",
      successCase: (res) => {
        if (active && res.data) setData(res.data);
      },
      errorCase: (res) => {
        if (active)
          setError(formatApiMsg(res.msg) || "تعذّر تحميل تفاصيل التسوية");
      },
    }).finally(() => {
      if (active) setLoading(false);
    });

    return () => {
      active = false;
    };
  }, [id]);

  if (error) {
    return (
      <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-8 text-center max-w-2xl mx-auto mt-8">
        <i className="ri-error-warning-line text-red-400 text-3xl mb-3 block" />
        <p className="text-red-400 text-sm mb-6">{error}</p>
        <button
          onClick={() => router.push("/settlements")}
          className="bg-white/5 hover:bg-white/10 text-white font-semibold text-sm px-6 py-2.5 rounded-xl cursor-pointer transition-colors"
        >
          العودة للتسويات
        </button>
      </div>
    );
  }

  if (loading || !data) {
    return (
      <div className="max-w-4xl mx-auto animate-pulse mt-8 space-y-6">
        <div className="h-32 bg-[#1E2128] rounded-2xl" />
        <div className="h-64 bg-[#1E2128] rounded-2xl" />
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      {/* Header / Summary */}
      <div className="bg-[#1E2128] rounded-2xl p-6">
        <div className="flex items-center justify-between mb-6 border-b border-white/5 pb-6">
          <div className="flex items-center gap-3">
            <Link
              href="/settlements"
              className="w-10 h-10 bg-white/5 hover:bg-white/10 rounded-xl flex items-center justify-center text-white transition-colors cursor-pointer"
            >
              <i className="ri-arrow-right-line text-lg" />
            </Link>
            <div>
              <h2 className="text-white font-bold text-xl">
                تفاصيل التسوية #{data.id}
              </h2>
              <div className="flex items-center gap-2 mt-1">
                <span className="text-gray-400 text-sm">
                  تاريخ الطلب: {data.requested_at}
                </span>
                {data.reviewed_at && (
                  <>
                    <span className="w-1 h-1 rounded-full bg-white/20" />
                    <span className="text-gray-400 text-sm">
                      تاريخ المراجعة: {data.reviewed_at}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
          <span
            className={`text-sm font-semibold px-4 py-1.5 rounded-full whitespace-nowrap ${getSettlementStatusClass(data.status)}`}
          >
            ● {data.status_label}
          </span>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          <div>
            <p className="text-gray-400 text-xs mb-1">المبلغ المحول</p>
            <p className="text-[#FCD704] font-black text-xl">
              {formatMoney(data.total_amount, data.currency)}
            </p>
          </div>
          <div>
            <p className="text-gray-400 text-xs mb-1">إجمالي الإيرادات</p>
            <p className="text-white font-bold text-lg">
              {formatMoney(data.total_revenue, data.currency)}
            </p>
          </div>
          <div>
            <p className="text-gray-400 text-xs mb-1">نسبة الأرباح</p>
            <p className="text-white font-bold text-lg">
              {formatProfitRate(data.profit_rate)}
            </p>
          </div>
          <div>
            <p className="text-gray-400 text-xs mb-1">عدد الرحلات</p>
            <p className="text-white font-bold text-lg">
              {data.rides_count} رحلة
            </p>
          </div>
        </div>

        {/* Status Specific Blocks */}
        {data.status === "rejected" && data.rejection_reason && (
          <div className="mt-6 bg-red-500/10 border border-red-500/20 rounded-xl p-4 flex gap-3">
            <i className="ri-error-warning-fill text-red-400 text-xl flex-shrink-0" />
            <div>
              <p className="text-red-400 font-bold text-sm mb-1">سبب الرفض</p>
              <p className="text-red-400/80 text-sm leading-relaxed whitespace-pre-wrap">
                {data.rejection_reason}
              </p>
            </div>
          </div>
        )}

        {data.status === "accepted" && data.transfer_proof_url && (
          <div className="mt-6 bg-green-500/10 border border-green-500/20 rounded-xl p-4 flex items-center justify-between gap-3">
            <div className="flex gap-3">
              <i className="ri-file-download-fill text-green-400 text-xl flex-shrink-0" />
              <div>
                <p className="text-green-400 font-bold text-sm mb-1">
                  إيصال التحويل
                </p>
                <p className="text-green-400/80 text-sm">
                  تم إرفاق إيصال التحويل البنكي
                </p>
              </div>
            </div>
            <a
              href={data.transfer_proof_url}
              target="_blank"
              rel="noopener noreferrer"
              className="bg-green-500/20 hover:bg-green-500/30 text-green-400 font-semibold text-sm px-4 py-2 rounded-xl transition-colors whitespace-nowrap"
            >
              عرض الإيصال
            </a>
          </div>
        )}
      </div>

      {/* Rides Sub-table */}
      <div className="bg-[#1E2128] rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/5 flex items-center gap-2">
          <h3 className="text-white font-bold text-lg">
            الرحلات المشمولة في التسوية
          </h3>
          <span className="bg-white/10 text-white text-xs px-2 py-0.5 rounded-md font-semibold">
            {data.rides?.length || 0}
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-right">
            <thead>
              <tr className="border-b border-white/5 bg-[#13151A]/50">
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  رقم الرحلة
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  المركبة
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  تكلفة الرحلة
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  المبلغ المستحق
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  تاريخ الانتهاء
                </th>
                <th className="text-gray-400 text-xs font-medium py-3 px-6">
                  المسار
                </th>
              </tr>
            </thead>
            <tbody>
              {!data.rides || data.rides.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-12 text-center">
                    <p className="text-gray-500 text-sm">
                      لا توجد بيانات للرحلات
                    </p>
                  </td>
                </tr>
              ) : (
                data.rides.map((ride, i) => (
                  <tr
                    key={ride.id || `${ride.scooter_code}-${i}`}
                    className="border-b border-white/5 last:border-0 hover:bg-white/2 transition-colors"
                  >
                    <td className="py-4 px-6">
                      <span className="text-white font-semibold text-sm">
                        # {ride.id}
                      </span>
                    </td>
                    <td className="py-4 px-6">
                      <span className="text-white font-semibold text-sm">
                        {ride.scooter_code}
                      </span>
                    </td>
                    <td className="py-4 px-6">
                      <span className="text-gray-300 text-sm">
                        {formatMoney(ride.ride_cost, data.currency)}
                      </span>
                    </td>
                    <td className="py-4 px-6">
                      <span className="text-[#FCD704] font-bold text-sm">
                        {formatMoney(ride.share_amount, data.currency)}
                      </span>
                    </td>
                    <td className="py-4 px-6">
                      <div className="flex items-center gap-1.5">
                        <i className="ri-time-line text-gray-500 text-xs" />
                        <span className="text-gray-400 text-sm" dir="ltr">
                          {new Date(ride.ended_at).toLocaleString("en-GB", {
                            day: "numeric",
                            month: "short",
                            year: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </span>
                      </div>
                    </td>
                    <td className="py-4 px-6 text-xs text-gray-400 w-64 max-w-xs">
                      <div className="flex flex-col gap-1">
                        <div className="flex items-start gap-1">
                          <span className="text-green-500 font-bold">•</span>
                          <span className="truncate" title={ride.start_address}>
                            {ride.start_address || "—"}
                          </span>
                        </div>
                        <span className="h-3 w-0.5 ms-0.5 bg-gray-600 rounded-full"></span>

                        <div className="flex items-center gap-1">
                          <span className="text-green-500 font-bold">•</span>
                          <span className="truncate" title={ride.end_address}>
                            {ride.end_address || "—"}
                          </span>
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default function SettlementDetailsPage() {
  return (
    <DashboardLayout
      title="تفاصيل التسوية"
      subtitle="عرض تفاصيل التسوية والرحلات المشمولة"
    >
      <Suspense
        fallback={
          <div className="max-w-4xl mx-auto animate-pulse mt-8 space-y-6">
            <div className="h-32 bg-[#1E2128] rounded-2xl" />
            <div className="h-64 bg-[#1E2128] rounded-2xl" />
          </div>
        }
      >
        <SettlementDetailsContent />
      </Suspense>
    </DashboardLayout>
  );
}
