"use client";
import { useState, useEffect } from "react";
import Image from "next/image";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { formatMoney } from "@/lib/format";

interface VehicleDetails {
  id: number | string;
  code: string;
  model: string;
  status: string;
  status_label: string;
  battery_percent: number;
  image: string | null;
  location: string;
  utilization_percent: number;
  currency: string;
  revenue: {
    today: number;
    week: number;
    month: number;
  };
  your_share: {
    today: number;
    month: number;
  };
  rides: {
    today: number;
    total: number;
    avg_duration_min: number;
  };
  recent_rides: Array<{
    amount: number;
    duration_minutes: number;
    ended_at: string;
  }>;
}

function getStatusColor(status: string): string {
  switch (status) {
    case "active":
      return "text-[#FCD704] bg-[#FCD704]/15";
    case "maintenance":
      return "text-orange-400 bg-orange-400/15";
    case "in_ride":
      return "text-blue-400 bg-blue-400/15";
    default:
      return "text-gray-400 bg-gray-400/15";
  }
}

function getBatteryColor(percent: number): string {
  if (percent > 50) {
    return "bg-[#FCD704]";
  }
  if (percent > 20) {
    return "bg-yellow-400";
  }
  return "bg-red-500";
}

function handleImageError(event: React.SyntheticEvent<HTMLImageElement>): void {
  event.currentTarget.style.display = "none";
  const sibling = event.currentTarget.nextElementSibling as HTMLElement | null;
  if (sibling) {
    sibling.style.display = "flex";
  }
}

function getRideKey(ride: VehicleDetails["recent_rides"][number]): string {
  return `${ride.ended_at}-${ride.amount}-${ride.duration_minutes}`;
}

function renderLoadingState() {
  return (
    <div className="text-center py-10">
      <i className="ri-loader-4-line animate-spin text-[#FCD704] text-3xl" />
    </div>
  );
}

function renderErrorState(error: string) {
  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>
  );
}

function VehicleDetailsBody({ details }: Readonly<{ details: VehicleDetails }>) {
  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          {details.image ? (
            <Image
              src={details.image}
              alt={details.code}
              width={64}
              height={64}
              unoptimized
              className="w-16 h-16 rounded-2xl object-cover bg-[#FCD704]/10"
              onError={handleImageError}
            />
          ) : null}
          <div
            className="w-16 h-16 bg-[#FCD704]/15 rounded-2xl items-center justify-center"
            style={{ display: details.image ? "none" : "flex" }}
          >
            <i className="ri-e-bike-line text-[#FCD704] text-3xl" />
          </div>

          <div>
            <h3 className="text-white font-bold text-lg">{details.code}</h3>
            <p className="text-gray-400 text-sm">{details.model}</p>
          </div>
        </div>

        <div className="text-left flex flex-col items-end gap-2">
          <span
            className={`text-xs font-semibold px-3 py-1.5 rounded-full ${getStatusColor(details.status)}`}
          >
            ● {details.status_label}
          </span>
          <div className="flex items-center gap-1.5 text-gray-400 text-sm">
            <span>{details.location}</span>
            <i className="ri-map-pin-line text-[#FCD704]" />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="bg-white/5 rounded-xl p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-white font-semibold">
              {details.battery_percent}% ⚡
            </span>
            <span className="text-gray-400 text-xs">البطارية</span>
          </div>
          <div className="h-2 bg-white/10 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full ${getBatteryColor(details.battery_percent)}`}
              style={{ width: `${details.battery_percent}%` }}
            />
          </div>
        </div>
        <div className="bg-white/5 rounded-xl p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-white font-semibold">
              {details.utilization_percent}%
            </span>
            <span className="text-gray-400 text-xs">الاستخدام</span>
          </div>
          <div className="h-2 bg-white/10 rounded-full overflow-hidden flex justify-end">
            <div
              className="h-full bg-[#FCD704] rounded-full"
              style={{ width: `${details.utilization_percent}%` }}
            />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white/5 rounded-xl p-4 col-span-3 grid grid-cols-3 gap-4 text-center">
          <div>
            <p className="text-gray-400 text-xs mb-1">الإيراد (اليوم)</p>
            <p className="text-white font-semibold">
              {formatMoney(details.revenue.today, details.currency)}
            </p>
          </div>
          <div className="border-x border-white/5">
            <p className="text-gray-400 text-xs mb-1">الإيراد (أسبوع)</p>
            <p className="text-white font-semibold">
              {formatMoney(details.revenue.week, details.currency)}
            </p>
          </div>
          <div>
            <p className="text-gray-400 text-xs mb-1">الإيراد (شهر)</p>
            <p className="text-white font-semibold">
              {formatMoney(details.revenue.month, details.currency)}
            </p>
          </div>
        </div>

        <div className="bg-[#FCD704]/10 border border-[#FCD704]/20 rounded-xl p-4 col-span-3 grid grid-cols-2 gap-4 text-center">
          <div className="border-l border-[#FCD704]/20">
            <p className="text-[#FCD704]/80 text-xs mb-1">نصيبك (اليوم)</p>
            <p className="text-[#FCD704] font-bold text-lg">
              {formatMoney(details.your_share.today, details.currency)}
            </p>
          </div>
          <div>
            <p className="text-[#FCD704]/80 text-xs mb-1">نصيبك (الشهر)</p>
            <p className="text-[#FCD704] font-bold text-lg">
              {formatMoney(details.your_share.month, details.currency)}
            </p>
          </div>
        </div>

        <div className="bg-white/5 rounded-xl p-4 col-span-3 grid grid-cols-3 gap-4 text-center">
          <div>
            <p className="text-gray-400 text-xs mb-1">رحلات اليوم</p>
            <p className="text-white font-semibold">{details.rides.today}</p>
          </div>
          <div className="border-x border-white/5">
            <p className="text-gray-400 text-xs mb-1">إجمالي الرحلات</p>
            <p className="text-white font-semibold">{details.rides.total}</p>
          </div>
          <div>
            <p className="text-gray-400 text-xs mb-1">متوسط المدة</p>
            <p className="text-white font-semibold">
              {details.rides.avg_duration_min} د
            </p>
          </div>
        </div>
      </div>

      {details.recent_rides.length > 0 && (
        <div>
          <h3 className="text-white font-bold mb-3">أحدث الرحلات</h3>
          <div className="bg-white/5 rounded-xl overflow-hidden">
            {details.recent_rides.map((ride) => (
              <div
                key={getRideKey(ride)}
                className="flex items-center justify-between p-3 border-b border-white/5 last:border-0"
              >
                <div className="text-right">
                  <p className="text-gray-400 text-xs" dir="ltr">
                    {ride.ended_at}
                  </p>
                </div>
                <div className="flex items-center gap-4 text-left">
                  <span className="text-white text-sm font-medium">
                    {ride.duration_minutes} د
                  </span>
                  <span className="text-[#FCD704] font-semibold text-sm w-16">
                    {formatMoney(ride.amount, details.currency)}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function renderVehicleContent({
  loading,
  error,
  details,
}: Readonly<{
  loading: boolean;
  error: string;
  details: VehicleDetails | null;
}>) {
  if (loading) {
    return renderLoadingState();
  }
  if (error) {
    return renderErrorState(error);
  }
  if (details) {
    return <VehicleDetailsBody details={details} />;
  }
  return null;
}

export default function VehicleDetailsModal({
  isOpen,
  onClose,
  vehicleId,
}: Readonly<{
  isOpen: boolean;
  onClose: () => void;
  vehicleId: number | string | null;
}>) {
  const [details, setDetails] = useState<VehicleDetails | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    let active = true;
    if (isOpen && vehicleId) {
      setLoading(true);
      setError("");
      apiFetch<VehicleDetails>(`/provider/vehicles/${vehicleId}`, {
        method: "GET",
        successCase: (res) => {
          if (active && res.data) {
            setDetails(res.data);
          }
        },
        errorCase: (res) => {
          if (active) {
            setError(formatApiMsg(res.msg) || "خطأ في جلب تفاصيل المركبة");
          }
        },
      }).finally(() => {
        if (active) {
          setLoading(false);
        }
      });
    }

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

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <button
        type="button"
        aria-label="إغلاق النافذة"
        className="absolute inset-0 bg-black/60 backdrop-blur-sm cursor-default"
        onClick={onClose}
        onKeyDown={(event) => {
          if (event.key === "Escape") {
            onClose();
          }
        }}
      />
      <dialog
        open
        className="relative bg-[#2A2D36] rounded-2xl w-full max-w-xl overflow-hidden flex flex-col max-h-[90vh] border-0 p-0 m-0"
      >
        <div className="flex items-center justify-between p-6 border-b border-white/5">
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-xl bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white transition-colors cursor-pointer"
          >
            <i className="ri-close-line text-lg" />
          </button>
          <h2 className="text-white font-bold text-lg">تفاصيل المركبة</h2>
        </div>

        <div className="p-6 overflow-y-auto">
          {renderVehicleContent({ loading, error, details })}
        </div>
      </dialog>
    </div>
  );
}
