"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import {
  Car,
  Plus,
  Settings,
  Loader2,
  Calendar,
  AlertTriangle,
  TrendingUp,
} from "lucide-react";
import dynamic from "next/dynamic";
import type { Lang } from "@/lib/config";
import type { VehicleRental, RentalStatus } from "@/lib/types/vehicles.types";
import {
  RENTAL_STATUS_CONFIG,
  formatVehiclePrice,
} from "@/lib/types/vehicles.types";

const FleetManagerModal = dynamic(
  () => import("./mobility/FleetManagerModal"),
  { ssr: false },
);
const NewRentalModal = dynamic(() => import("./mobility/NewRentalModal"), {
  ssr: false,
});
const RentalDetailModal = dynamic(
  () => import("./mobility/RentalDetailModal"),
  { ssr: false },
);

const FILTER_OPTIONS: (RentalStatus | "all")[] = [
  "all",
  "pending",
  "confirmed",
  "active",
  "completed",
  "cancelled",
  "overdue",
];

interface RentalsPanelProps {
  lang: Lang;
}

function formatDateShort(ts: number): string {
  return new Date(ts).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}

export default function RentalsPanel({ lang }: RentalsPanelProps) {
  const isAr = lang === "ar";
  const [rentals, setRentals] = useState<VehicleRental[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<RentalStatus | "all">("all");
  const [showFleetModal, setShowFleetModal] = useState(false);
  const [showNewRentalModal, setShowNewRentalModal] = useState(false);
  const [selectedRental, setSelectedRental] = useState<VehicleRental | null>(
    null,
  );

  const fetchRentals = useCallback(async () => {
    setLoading(true);
    try {
      const url =
        filter === "all"
          ? "/api/dashboard/rentals"
          : `/api/dashboard/rentals?status=${filter}`;
      const res = await fetch(url);
      if (res.ok) {
        const data = await res.json();
        setRentals(data.rentals ?? []);
      }
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => {
    fetchRentals();
  }, [fetchRentals]);

  // Stats
  const stats = useMemo(() => {
    const now = Date.now();
    const active = rentals.filter((r) => r.status === "active").length;
    const upcoming = rentals.filter(
      (r) => r.status === "confirmed" && r.pickupDate > now,
    ).length;
    const overdue = rentals.filter((r) => r.status === "overdue").length;
    const revenue = rentals.reduce((sum, r) => sum + (r.amountPaid || 0), 0);
    return { active, upcoming, overdue, revenue };
  }, [rentals]);

  const handleRentalClick = (rental: VehicleRental) => {
    setSelectedRental(rental);
  };

  const handleRentalUpdated = () => {
    setSelectedRental(null);
    fetchRentals();
  };

  const filterLabels: Record<string, { en: string; ar: string }> = {
    all: { en: "All", ar: "الكل" },
    pending: { en: "Pending", ar: "معلق" },
    confirmed: { en: "Confirmed", ar: "مؤكد" },
    active: { en: "Active", ar: "نشط" },
    completed: { en: "Completed", ar: "مكتمل" },
    cancelled: { en: "Cancelled", ar: "ملغى" },
    overdue: { en: "Overdue", ar: "متأخر" },
  };

  return (
    <div className="space-y-6">
      {/* Stats Row */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="flex items-center gap-2 mb-1">
            <Car className="w-4 h-4 text-green-500" />
            <span className="text-xs text-slate-500">
              {isAr ? "نشط" : "Active"}
            </span>
          </div>
          <p className="text-2xl font-bold text-slate-900">{stats.active}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="flex items-center gap-2 mb-1">
            <Calendar className="w-4 h-4 text-blue-500" />
            <span className="text-xs text-slate-500">
              {isAr ? "قادم" : "Upcoming"}
            </span>
          </div>
          <p className="text-2xl font-bold text-slate-900">{stats.upcoming}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="flex items-center gap-2 mb-1">
            <AlertTriangle className="w-4 h-4 text-orange-500" />
            <span className="text-xs text-slate-500">
              {isAr ? "متأخر" : "Overdue"}
            </span>
          </div>
          <p className="text-2xl font-bold text-slate-900">{stats.overdue}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="w-4 h-4 text-brand-green" />
            <span className="text-xs text-slate-500">
              {isAr ? "الإيرادات" : "Revenue"}
            </span>
          </div>
          <p className="text-2xl font-bold text-slate-900">
            {formatVehiclePrice(stats.revenue, "QAR")}
          </p>
        </div>
      </div>

      {/* Actions & Filters */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowFleetModal(true)}
            className="flex items-center gap-2 px-4 py-2 border border-slate-200 rounded-lg text-sm text-slate-700 hover:bg-slate-50"
          >
            <Settings className="w-4 h-4" />
            {isAr ? "إدارة الأسطول" : "Manage Fleet"}
          </button>
          <button
            onClick={() => setShowNewRentalModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90"
          >
            <Plus className="w-4 h-4" />
            {isAr ? "حجز جديد" : "New Rental"}
          </button>
        </div>

        <div className="flex flex-wrap items-center gap-1.5">
          {FILTER_OPTIONS.map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
                filter === f
                  ? "bg-brand-green text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {isAr ? filterLabels[f].ar : filterLabels[f].en}
            </button>
          ))}
        </div>
      </div>

      {/* Rental List */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
          </div>
        ) : rentals.length === 0 ? (
          <div className="text-center py-16">
            <Car className="w-12 h-12 text-slate-300 mx-auto mb-3" />
            <p className="text-slate-500 text-sm">
              {isAr ? "لا توجد حجوزات" : "No rentals found"}
            </p>
            <button
              onClick={() => setShowNewRentalModal(true)}
              className="mt-3 text-sm text-brand-green hover:underline"
            >
              {isAr ? "أنشئ أول حجز" : "Create your first rental"}
            </button>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {rentals.map((rental) => {
              const statusCfg = RENTAL_STATUS_CONFIG[rental.status];
              return (
                <button
                  key={rental._id}
                  onClick={() => handleRentalClick(rental)}
                  className="w-full text-left px-5 py-4 hover:bg-slate-50 transition-colors flex items-center justify-between gap-4"
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0">
                      <Car className="w-5 h-5 text-slate-500" />
                    </div>
                    <div className="min-w-0">
                      <p className="font-medium text-slate-900 text-sm truncate">
                        {rental.vehicle
                          ? `${rental.vehicle.make} ${rental.vehicle.model} ${rental.vehicle.year}`
                          : rental.vehicleId}
                      </p>
                      <p className="text-xs text-slate-500 truncate">
                        {rental.customerName} · {rental.customerPhone}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 flex-shrink-0">
                    <div className="text-right hidden sm:block">
                      <p className="text-xs text-slate-500">
                        {formatDateShort(rental.pickupDate)} →{" "}
                        {formatDateShort(rental.returnDate)}
                      </p>
                      <p className="text-xs font-medium text-slate-700">
                        {formatVehiclePrice(
                          rental.totalAmount,
                          rental.currency,
                        )}
                      </p>
                    </div>
                    <span
                      className={`px-2.5 py-1 rounded-full text-xs font-medium whitespace-nowrap ${statusCfg.color}`}
                    >
                      {isAr ? statusCfg.label.ar : statusCfg.label.en}
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Modals */}
      <FleetManagerModal
        lang={lang}
        isOpen={showFleetModal}
        onClose={() => setShowFleetModal(false)}
        onFleetUpdated={fetchRentals}
      />
      <NewRentalModal
        lang={lang}
        isOpen={showNewRentalModal}
        onClose={() => setShowNewRentalModal(false)}
        onCreated={() => {
          setShowNewRentalModal(false);
          fetchRentals();
        }}
      />
      <RentalDetailModal
        lang={lang}
        isOpen={!!selectedRental}
        onClose={() => setSelectedRental(null)}
        rental={selectedRental}
        onUpdated={handleRentalUpdated}
      />
    </div>
  );
}
