"use client";

import { Search, Phone, Ticket, ChevronRight, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { apiClient } from "@/lib/api-client";
import { format } from "date-fns";
import { toZonedDate } from "@/utils/format";

type SearchMode = "pnr" | "phone";

interface BookingListItem {
  id: string;
  bookingRef: string;
  status: string;
  totalMinor: number;
  currency: string;
  displayCurrency?: string | null;
  displayTotalMinor?: number | null;
  adultCount: number;
  childCount: number;
  bookingType: string;
  createdAt: string;
  schedule: {
    originStation: { name: string; city?: string };
    destinationStation: { name: string; city?: string };
    departureAt: string;
  };
  payment?: { method: string; status: string };
  seatCount: number;
}

const STATUS_LABELS: Record<string, { label: string; className: string }> = {
  CONFIRMED:       { label: "Confirmed",       className: "bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300" },
  PENDING_PAYMENT: { label: "Pending Payment", className: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-300" },
  CANCELLED:       { label: "Cancelled",       className: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300" },
  BOARDED:         { label: "Boarded",         className: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300" },
  NO_SHOW:         { label: "No Show",         className: "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300" },
  REFUNDED:        { label: "Refunded",        className: "bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300" },
};

export default function BookingLookupPage() {
  const router = useRouter();
  const [mode, setMode] = useState<SearchMode>("pnr");

  // PNR mode state
  const [bookingRef, setBookingRef] = useState("");

  // Phone mode state
  const [phone, setPhone] = useState("");
  const [phoneResults, setPhoneResults] = useState<BookingListItem[] | null>(null);
  const [phoneLoading, setPhoneLoading] = useState(false);

  const [error, setError] = useState("");

  // ── PNR submit ───────────────────────────────────────────────────────────
  const handlePnrSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = bookingRef.trim().toUpperCase();
    if (!trimmed) { setError("Please enter a booking reference"); return; }
    router.push(`/booking/detail?ref=${trimmed}`);
  };

  // ── Phone submit ─────────────────────────────────────────────────────────
  const handlePhoneSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = phone.trim();
    if (!trimmed) { setError("Please enter your phone number"); return; }
    const digits = trimmed.replace(/[^\d]/g, "");
    if (digits.length < 7) { setError("Please enter a valid phone number"); return; }

    setError("");
    setPhoneLoading(true);
    setPhoneResults(null);
    try {
      const resp: any = await apiClient.get(`/bookings/by-phone?phone=${encodeURIComponent(trimmed)}`);
      const items: BookingListItem[] = (resp as any)?.data?.items ?? (resp as any)?.items ?? [];
      setPhoneResults(items);
      if (items.length === 0) setError("No bookings found for this phone number");
    } catch {
      setError("Could not look up bookings. Please check your number and try again.");
    } finally {
      setPhoneLoading(false);
    }
  };

  const switchMode = (next: SearchMode) => {
    setMode(next);
    setError("");
    setPhoneResults(null);
    setBookingRef("");
    setPhone("");
  };

  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center p-4 bg-gray-50 dark:bg-gray-900">
      <div className="w-full max-w-md">
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8">
          {/* Header */}
          <div className="text-center mb-6">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-[rgb(20,113,76)] bg-opacity-10 rounded-full mb-4">
              <Search className="w-8 h-8 text-[rgb(20,113,76)]" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Find Your Booking
            </h1>
            <p className="text-gray-600 dark:text-gray-400 text-sm">
              Search by booking reference or phone number
            </p>
          </div>

          {/* Mode tabs */}
          <div className="flex rounded-lg border border-gray-200 dark:border-gray-700 mb-6 overflow-hidden">
            <button
              onClick={() => switchMode("pnr")}
              className={`flex-1 flex items-center justify-center gap-2 py-2.5 text-sm font-medium transition-colors ${
                mode === "pnr"
                  ? "bg-[rgb(20,113,76)] text-white"
                  : "text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
              }`}
            >
              <Ticket className="w-4 h-4" />
              Booking Ref (PNR)
            </button>
            <button
              onClick={() => switchMode("phone")}
              className={`flex-1 flex items-center justify-center gap-2 py-2.5 text-sm font-medium transition-colors ${
                mode === "phone"
                  ? "bg-[rgb(20,113,76)] text-white"
                  : "text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
              }`}
            >
              <Phone className="w-4 h-4" />
              Phone Number
            </button>
          </div>

          {/* ── PNR form ── */}
          {mode === "pnr" && (
            <form onSubmit={handlePnrSubmit}>
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Booking Reference (PNR)
                </label>
                <input
                  type="text"
                  value={bookingRef}
                  onChange={(e) => { setBookingRef(e.target.value.toUpperCase()); setError(""); }}
                  placeholder="e.g. ABCXYZ"
                  className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-[rgb(20,113,76)] focus:border-transparent dark:bg-gray-700 dark:text-white text-lg font-mono uppercase tracking-widest"
                />
                {error && <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>}
              </div>
              <button
                type="submit"
                className="w-full bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-medium py-3 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                <Search className="w-5 h-5" />
                Search Booking
              </button>
            </form>
          )}

          {/* ── Phone form ── */}
          {mode === "phone" && (
            <>
              <form onSubmit={handlePhoneSubmit}>
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Phone Number
                  </label>
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => { setPhone(e.target.value); setError(""); setPhoneResults(null); }}
                    placeholder="Enter phone number"
                    className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-[rgb(20,113,76)] focus:border-transparent dark:bg-gray-700 dark:text-white text-lg"
                  />
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Enter the phone number you used when booking
                  </p>
                  {error && <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>}
                </div>
                <button
                  type="submit"
                  disabled={phoneLoading}
                  className="w-full bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] disabled:opacity-60 text-white font-medium py-3 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
                >
                  {phoneLoading ? (
                    <><Loader2 className="w-5 h-5 animate-spin" /> Searching…</>
                  ) : (
                    <><Search className="w-5 h-5" /> Find Bookings</>
                  )}
                </button>
              </form>

              {/* Results list */}
              {phoneResults !== null && phoneResults.length > 0 && (
                <div className="mt-6 space-y-3">
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    {phoneResults.length} booking{phoneResults.length !== 1 ? "s" : ""} found — select one to view details:
                  </p>
                  {phoneResults.map((b) => {
                    const statusInfo = STATUS_LABELS[b.status] ?? { label: b.status, className: "bg-gray-100 text-gray-700" };
                    const displayCurrency = b.displayCurrency || 'ETB';
                    const displayAmount = ((b.displayTotalMinor ?? b.totalMinor) / 100).toLocaleString("en-ET", { minimumFractionDigits: 2 });
                    return (
                      <button
                        key={b.id}
                        onClick={() => router.push(`/booking/detail?ref=${b.bookingRef}`)}
                        className="w-full text-left border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-[rgb(20,113,76)] hover:bg-green-50 dark:hover:bg-green-900/10 transition-colors group"
                      >
                        <div className="flex items-start justify-between gap-2">
                          <div className="min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-mono font-bold text-gray-900 dark:text-white tracking-wider">
                                {b.bookingRef}
                              </span>
                              <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${statusInfo.className}`}>
                                {statusInfo.label}
                              </span>
                            </div>
                            <p className="text-sm text-gray-700 dark:text-gray-300 truncate">
                              {b.schedule.originStation.name} → {b.schedule.destinationStation.name}
                            </p>
                            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                              {format(toZonedDate(new Date(b.schedule.departureAt)), "dd MMM yyyy, HH:mm")}
                              {" · "}
                              {b.adultCount} adult{b.adultCount !== 1 ? "s" : ""}
                              {b.childCount > 0 && `, ${b.childCount} child${b.childCount !== 1 ? "ren" : ""}`}
                            </p>
                          </div>
                          <div className="flex flex-col items-end gap-1 flex-shrink-0">
                            <span className="text-sm font-semibold text-gray-900 dark:text-white whitespace-nowrap">
                              {displayAmount} {displayCurrency}
                            </span>
                            <ChevronRight className="w-4 h-4 text-gray-400 group-hover:text-[rgb(20,113,76)] transition-colors" />
                          </div>
                        </div>
                      </button>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
