"use client";

import { useState } from "react";
import {
  X,
  Loader2,
  Car,
  Phone,
  Mail,
  Calendar,
  CreditCard,
  FileText,
  Send,
  CheckCircle,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
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";

interface RentalDetailModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  rental: VehicleRental | null;
  onUpdated: () => void;
}

const STATUS_ACTIONS: Record<
  RentalStatus,
  { label: { en: string; ar: string }; nextStatus: string }[]
> = {
  pending: [
    { label: { en: "Confirm", ar: "تأكيد" }, nextStatus: "confirmed" },
    { label: { en: "Cancel", ar: "إلغاء" }, nextStatus: "cancelled" },
  ],
  confirmed: [
    {
      label: { en: "Mark Active (Collected)", ar: "تم الاستلام" },
      nextStatus: "active",
    },
    { label: { en: "Cancel", ar: "إلغاء" }, nextStatus: "cancelled" },
  ],
  active: [
    {
      label: { en: "Complete Return", ar: "تم الإرجاع" },
      nextStatus: "completed",
    },
    { label: { en: "Mark Overdue", ar: "متأخر" }, nextStatus: "overdue" },
  ],
  completed: [],
  cancelled: [],
  overdue: [],
};

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

export default function RentalDetailModal({
  lang,
  isOpen,
  onClose,
  rental,
  onUpdated,
}: RentalDetailModalProps) {
  const isAr = lang === "ar";
  const [updating, setUpdating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showReturnDate, setShowReturnDate] = useState(false);
  const [actualReturnDate, setActualReturnDate] = useState("");
  const [sendingDepositLink, setSendingDepositLink] = useState(false);
  const [depositLinkSent, setDepositLinkSent] = useState(false);

  if (!isOpen || !rental) return null;

  const statusConfig = RENTAL_STATUS_CONFIG[rental.status];
  const actions = STATUS_ACTIONS[rental.status] || [];

  const handleStatusChange = async (nextStatus: string) => {
    if (nextStatus === "completed" && !showReturnDate) {
      setShowReturnDate(true);
      setActualReturnDate(new Date().toISOString().split("T")[0]);
      return;
    }

    setUpdating(true);
    setError(null);
    try {
      const body: Record<string, unknown> = { status: nextStatus };
      if (nextStatus === "completed" && actualReturnDate) {
        body.actualReturnDate = new Date(actualReturnDate).getTime();
      }

      const res = await fetchWithCSRF(`/api/dashboard/rentals/${rental._id}`, {
        method: "PUT",
        body: JSON.stringify(body),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to update");
      }

      setShowReturnDate(false);
      onUpdated();
    } catch (e) {
      setError(
        e instanceof Error ? e.message : isAr ? "حدث خطأ" : "An error occurred",
      );
    } finally {
      setUpdating(false);
    }
  };

  const handleSendDepositLink = async () => {
    if (!rental.customerEmail || !rental.depositAmount) return;
    setSendingDepositLink(true);
    setError(null);
    try {
      const vehicleName = rental.vehicle
        ? `${rental.vehicle.make} ${rental.vehicle.model} ${rental.vehicle.year}`
        : undefined;
      const res = await fetchWithCSRF("/api/dashboard/rentals/deposit-link", {
        method: "POST",
        body: JSON.stringify({
          rentalId: rental._id,
          customerEmail: rental.customerEmail,
          customerName: rental.customerName,
          depositAmount: rental.depositAmount / 100,
          vehicleName,
          agreementNumber: undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "Failed to send deposit link");
      }
      setDepositLinkSent(true);
    } catch (e) {
      setError(
        e instanceof Error ? e.message : isAr ? "حدث خطأ" : "An error occurred",
      );
    } finally {
      setSendingDepositLink(false);
    }
  };

  const inputClass =
    "w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div className="flex items-center gap-3">
            <span
              className={`px-3 py-1 rounded-full text-xs font-medium ${statusConfig.color}`}
            >
              {isAr ? statusConfig.label.ar : statusConfig.label.en}
            </span>
            <h2 className="text-lg font-semibold text-slate-900">
              {isAr ? "تفاصيل الحجز" : "Rental Details"}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 rounded-lg"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-6 space-y-5">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
              {error}
            </div>
          )}

          {/* Vehicle Info */}
          {rental.vehicle && (
            <div className="flex items-center gap-3 p-3 bg-slate-50 rounded-lg">
              <Car className="w-5 h-5 text-slate-500" />
              <div>
                <p className="font-medium text-sm text-slate-900">
                  {rental.vehicle.make} {rental.vehicle.model}{" "}
                  {rental.vehicle.year}
                </p>
                {rental.vehicle.licensePlate && (
                  <p className="text-xs text-slate-500">
                    {rental.vehicle.licensePlate}
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Customer Info */}
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-slate-700 flex items-center gap-1">
              <FileText className="w-4 h-4" />
              {isAr ? "بيانات العميل" : "Customer Info"}
            </h3>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <p className="text-xs text-slate-500">
                  {isAr ? "الاسم" : "Name"}
                </p>
                <p className="font-medium text-slate-900">
                  {rental.customerName}
                </p>
              </div>
              <div>
                <p className="text-xs text-slate-500 flex items-center gap-1">
                  <Phone className="w-3 h-3" />
                  {isAr ? "الهاتف" : "Phone"}
                </p>
                <p className="font-medium text-slate-900">
                  {rental.customerPhone}
                </p>
              </div>
              {rental.customerEmail && (
                <div>
                  <p className="text-xs text-slate-500 flex items-center gap-1">
                    <Mail className="w-3 h-3" />
                    {isAr ? "البريد" : "Email"}
                  </p>
                  <p className="font-medium text-slate-900">
                    {rental.customerEmail}
                  </p>
                </div>
              )}
              {rental.customerLicenseNumber && (
                <div>
                  <p className="text-xs text-slate-500">
                    {isAr ? "رقم الرخصة" : "License"}
                  </p>
                  <p className="font-medium text-slate-900">
                    {rental.customerLicenseNumber}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Dates */}
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-slate-700 flex items-center gap-1">
              <Calendar className="w-4 h-4" />
              {isAr ? "التواريخ" : "Dates"}
            </h3>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <p className="text-xs text-slate-500">
                  {isAr ? "الاستلام" : "Pickup"}
                </p>
                <p className="font-medium text-slate-900">
                  {formatDate(rental.pickupDate)}
                </p>
              </div>
              <div>
                <p className="text-xs text-slate-500">
                  {isAr ? "الإرجاع" : "Return"}
                </p>
                <p className="font-medium text-slate-900">
                  {formatDate(rental.returnDate)}
                </p>
              </div>
              {rental.actualReturnDate && (
                <div>
                  <p className="text-xs text-slate-500">
                    {isAr ? "الإرجاع الفعلي" : "Actual Return"}
                  </p>
                  <p className="font-medium text-slate-900">
                    {formatDate(rental.actualReturnDate)}
                  </p>
                </div>
              )}
              <div>
                <p className="text-xs text-slate-500">
                  {isAr ? "المدة" : "Duration"}
                </p>
                <p className="font-medium text-slate-900">
                  {rental.durationDays} {isAr ? "يوم" : "days"}
                </p>
              </div>
            </div>
          </div>

          {/* Pricing */}
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-slate-700 flex items-center gap-1">
              <CreditCard className="w-4 h-4" />
              {isAr ? "التسعير" : "Pricing"}
            </h3>
            <div className="border border-slate-200 rounded-lg p-3 space-y-1 text-sm">
              <div className="flex justify-between">
                <span className="text-slate-500">
                  {isAr ? "السعر اليومي" : "Daily Rate"}
                </span>
                <span>
                  {formatVehiclePrice(rental.dailyRate, rental.currency)}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-500">
                  {isAr ? "الإجمالي" : "Total"}
                </span>
                <span className="font-semibold">
                  {formatVehiclePrice(rental.totalAmount, rental.currency)}
                </span>
              </div>
              {rental.depositAmount != null && rental.depositAmount > 0 && (
                <div className="flex justify-between">
                  <span className="text-slate-500">
                    {isAr ? "التأمين" : "Deposit"}
                  </span>
                  <span>
                    {formatVehiclePrice(rental.depositAmount, rental.currency)}
                  </span>
                </div>
              )}
              <div className="flex justify-between border-t pt-1">
                <span className="text-slate-500">
                  {isAr ? "المدفوع" : "Paid"}
                </span>
                <span className="font-medium text-green-600">
                  {formatVehiclePrice(rental.amountPaid, rental.currency)}
                </span>
              </div>
            </div>
          </div>

          {/* Send Deposit Payment Link */}
          {rental.depositAmount != null &&
            rental.depositAmount > 0 &&
            !rental.depositPaid &&
            rental.customerEmail &&
            rental.status !== "cancelled" &&
            rental.status !== "completed" && (
              <div className="border border-blue-200 rounded-lg p-4 bg-blue-50/50 space-y-2">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-slate-900">
                      {isAr ? "إرسال رابط دفع التأمين" : "Send Deposit Payment Link"}
                    </p>
                    <p className="text-xs text-slate-500">
                      {isAr ? "سيُرسل إلى" : "Will be sent to"}{" "}
                      {rental.customerEmail}
                    </p>
                  </div>
                  {depositLinkSent ? (
                    <span className="flex items-center gap-1 text-green-600 text-sm font-medium">
                      <CheckCircle className="w-4 h-4" />
                      {isAr ? "تم الإرسال" : "Sent"}
                    </span>
                  ) : (
                    <button
                      onClick={handleSendDepositLink}
                      disabled={sendingDepositLink}
                      className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
                    >
                      {sendingDepositLink ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Send className="w-4 h-4" />
                      )}
                      {isAr ? "إرسال" : "Send Link"}
                    </button>
                  )}
                </div>
              </div>
            )}

          {/* Notes */}
          {rental.notes && (
            <div>
              <p className="text-xs text-slate-500 mb-1">
                {isAr ? "ملاحظات" : "Notes"}
              </p>
              <p className="text-sm text-slate-700 bg-slate-50 rounded-lg p-3">
                {rental.notes}
              </p>
            </div>
          )}

          {/* Return date input for completion */}
          {showReturnDate && (
            <div className="border border-brand-green/30 rounded-lg p-4 bg-brand-green/5 space-y-2">
              <label className="text-sm font-medium text-slate-700">
                {isAr ? "تاريخ الإرجاع الفعلي" : "Actual Return Date"}
              </label>
              <input
                type="date"
                value={actualReturnDate}
                onChange={(e) => setActualReturnDate(e.target.value)}
                className={inputClass}
              />
              <button
                onClick={() => handleStatusChange("completed")}
                disabled={updating || !actualReturnDate}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 disabled:opacity-50"
              >
                {updating && <Loader2 className="w-4 h-4 animate-spin" />}
                {isAr ? "تأكيد الإرجاع" : "Confirm Return"}
              </button>
            </div>
          )}
        </div>

        {/* Action buttons */}
        {actions.length > 0 && !showReturnDate && (
          <div className="p-6 border-t flex items-center gap-2 justify-end">
            {actions.map((action) => (
              <button
                key={action.nextStatus}
                onClick={() => handleStatusChange(action.nextStatus)}
                disabled={updating}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50 ${
                  action.nextStatus === "cancelled"
                    ? "border border-red-200 text-red-600 hover:bg-red-50"
                    : "bg-brand-green text-white hover:bg-brand-green/90"
                }`}
              >
                {updating && <Loader2 className="w-4 h-4 animate-spin" />}
                {isAr ? action.label.ar : action.label.en}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
