"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { CheckCircle, Clock, AlertCircle, Ban, Armchair, Download } from "lucide-react";
import { apiClient } from "@/lib/api-client";
import Badge from "@/components/ui/Badge";
import ActionButton from "@/components/ui/ActionButton";
import { formatDateTime, formatCurrency } from "@/lib/utils";
import Pagination from "@/components/ui/Pagination";
import { usePagination } from "@/lib/use-pagination";

interface ScheduleOption {
  id: string;
  label: string;
}

interface SeatRow {
  bookingRef: string;
  passengerName: string;
  passengerCategory: string;
  coachNumber: string | null;
  seatNumber: string | null;
  seatClassName: string | null;
  fareMinor: number;
  currency: string;
  bookingStatus: string;
  paymentStatus: string;
  bookedAt: string;
}

interface BlockedRow {
  id: string;
  coachNumber: string | null;
  seatNumber: string | null;
  seatClassName: string | null;
  reason: string;
  blockedBy: string;
  blockedAt: string;
  unblockAt: string | null;
}

interface SeatStatusReport {
  summary: {
    paidCount: number;
    unpaidCount: number;
    expiredHoldCount: number;
    blockedCount: number;
  };
  paidSeats: SeatRow[];
  unpaidSeats: SeatRow[];
  expiredHolds: { holdId: string; seatIds: string[]; expiresAt: string; createdAt: string }[];
  blockedSeats: BlockedRow[];
}

type Tab = "seats" | "blocked";

export default function SeatStatusReportPage() {
  const [scheduleId, setScheduleId] = useState("");
  const [tab, setTab] = useState<Tab>("seats");
  const [statusFilter, setStatusFilter] = useState<"ALL" | "PAID" | "UNPAID">("ALL");
  const [search, setSearch] = useState("");

  const { data: schedulesRaw, isLoading: loadingSchedules } = useQuery<ScheduleOption[]>({
    queryKey: ["report-schedules-all"],
    queryFn: () => apiClient.get("/reports/schedules?all=true"),
  });
  const schedules = schedulesRaw ?? [];

  const { data, isLoading, isError } = useQuery<SeatStatusReport>({
    queryKey: ["seat-status-report", scheduleId],
    queryFn: () => apiClient.get(`/reports/seat-status?scheduleId=${scheduleId}`),
    enabled: !!scheduleId,
  });

  const allSeats: SeatRow[] = [
    ...(data?.paidSeats ?? []),
    ...(data?.unpaidSeats ?? []),
  ];

  const filtered = allSeats.filter((r) => {
    const isPaid = r.bookingStatus === "CONFIRMED" || r.bookingStatus === "BOARDED";
    if (statusFilter === "PAID" && !isPaid) return false;
    if (statusFilter === "UNPAID" && isPaid) return false;
    if (search.trim()) {
      const q = search.toLowerCase();
      return (
        r.bookingRef.toLowerCase().includes(q) ||
        r.passengerName.toLowerCase().includes(q) ||
        (r.seatNumber ?? "").toLowerCase().includes(q) ||
        (r.coachNumber ?? "").toLowerCase().includes(q)
      );
    }
    return true;
  });

  const { paged: pagedSeats, page: seatsPage, totalPages: seatsTotalPages, setPage: setSeatsPage, reset: resetSeatsPage } = usePagination(filtered, 50);
  const { paged: pagedBlocked, page: blockedPage, totalPages: blockedTotalPages, setPage: setBlockedPage } = usePagination(data?.blockedSeats ?? [], 50);

  const doExport = () => {
    if (!filtered.length) return;
    const headers = ["Booking Ref", "Passenger", "Category", "Seat Class", "Coach", "Seat", "Fare", "Payment", "Booking Status", "Booked At"];
    const rows = filtered.map((r) => [
      r.bookingRef,
      r.passengerName,
      r.passengerCategory,
      r.seatClassName ?? "—",
      r.coachNumber ?? "—",
      r.seatNumber ?? "—",
      formatCurrency(r.fareMinor, r.currency),
      r.paymentStatus,
      r.bookingStatus,
      r.bookedAt ? formatDateTime(r.bookedAt) : "—",
    ]);
    const csv = [
      headers.map((h) => `"${h}"`).join(","),
      ...rows.map((row) => row.map((v) => `"${v}"`).join(",")),
    ].join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `seat-status-${scheduleId}-${new Date().toISOString().split("T")[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Seat Status Report</h1>
        <p className="text-muted-foreground mt-1">
          Paid, unpaid, expired holds and blocked seats for a schedule
        </p>
      </div>

      {/* Schedule selector */}
      <div className="card">
        <div className="flex items-end gap-4 flex-wrap">
          <div className="flex-1 min-w-72">
            <label className="label">Schedule</label>
            <select
              className="input"
              value={scheduleId}
              onChange={(e) => {
                setScheduleId(e.target.value);
                setTab("seats");
                setStatusFilter("ALL");
                setSearch("");
              }}
              disabled={loadingSchedules}
            >
              <option value="">
                {loadingSchedules ? "Loading schedules…" : "Select a schedule…"}
              </option>
              {schedules.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.label}
                </option>
              ))}
            </select>
          </div>
        </div>
        {isLoading && <p className="text-xs text-muted-foreground mt-2">Loading…</p>}
        {isError && <p className="text-xs text-red-500 mt-2">Failed to load report.</p>}
      </div>

      {!scheduleId && (
        <div className="card py-16 text-center text-muted-foreground">
          <Armchair className="h-10 w-10 mx-auto mb-3 opacity-30" />
          <p>Select a schedule above to load the seat status report</p>
        </div>
      )}

      {data && (
        <>
          {/* Summary Cards */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="card">
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-muted-foreground text-sm font-medium">Paid Seats</p>
                  <p className="text-2xl font-bold mt-2 text-green-600 dark:text-green-400">
                    {data.summary.paidCount}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">Payment confirmed</p>
                </div>
                <CheckCircle className="h-8 w-8 text-green-500 opacity-30" />
              </div>
            </div>

            <div className="card">
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-muted-foreground text-sm font-medium">Unpaid Seats</p>
                  <p className="text-2xl font-bold mt-2 text-amber-600 dark:text-amber-400">
                    {data.summary.unpaidCount}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">Awaiting payment</p>
                </div>
                <Clock className="h-8 w-8 text-amber-500 opacity-30" />
              </div>
            </div>

            <div className="card">
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-muted-foreground text-sm font-medium">Expired Holds</p>
                  <p className="text-2xl font-bold mt-2 text-red-600 dark:text-red-400">
                    {data.summary.expiredHoldCount}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">Hold time passed</p>
                </div>
                <AlertCircle className="h-8 w-8 text-red-500 opacity-30" />
              </div>
            </div>

            <div className="card">
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-muted-foreground text-sm font-medium">Blocked Seats</p>
                  <p className="text-2xl font-bold mt-2 text-slate-600 dark:text-slate-400">
                    {data.summary.blockedCount}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">Manually blocked</p>
                </div>
                <Ban className="h-8 w-8 text-slate-500 opacity-30" />
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div className="border-b border-border flex">
            <button
              onClick={() => setTab("seats")}
              className={`px-5 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === "seats" ? "border-emerald-500 text-emerald-600 dark:text-emerald-400" : "border-transparent text-muted-foreground hover:text-foreground"}`}
            >
              Seat Details{allSeats.length > 0 ? ` (${allSeats.length})` : ""}
            </button>
            <button
              onClick={() => setTab("blocked")}
              className={`px-5 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === "blocked" ? "border-emerald-500 text-emerald-600 dark:text-emerald-400" : "border-transparent text-muted-foreground hover:text-foreground"}`}
            >
              Blocked Seats{data.blockedSeats.length > 0 ? ` (${data.blockedSeats.length})` : ""}
            </button>
          </div>

          {/* Seat Details Tab */}
          {tab === "seats" && <div className="card p-0">
            <div className="flex items-center justify-between px-4 pt-4 pb-3 gap-4 flex-wrap">
              <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
                Seat Details
              </h3>
              <div className="flex items-center gap-3 flex-wrap">
                <input
                  type="text"
                  className="input max-w-xs"
                  placeholder="Booking ref, passenger, seat…"
                  value={search}
                  onChange={(e) => { setSearch(e.target.value); resetSeatsPage(); }}
                />
                <select
                  className="input w-40"
                  value={statusFilter}
                  onChange={(e) => { setStatusFilter(e.target.value as "ALL" | "PAID" | "UNPAID"); resetSeatsPage(); }}
                >
                  <option value="ALL">All Seats</option>
                  <option value="PAID">Paid Only</option>
                  <option value="UNPAID">Unpaid Only</option>
                </select>
                <ActionButton icon={Download} variant="secondary" onClick={doExport} disabled={!filtered.length}>
                  Export CSV
                </ActionButton>
              </div>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 dark:bg-gray-800">
                  <tr>
                    {["Booking Ref", "Passenger", "Category", "Seat Class · Coach · Seat", "Fare", "Payment", "Booked At"].map((h) => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400 whitespace-nowrap">
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                  {pagedSeats.map((row, i) => {
                    const isPaid = row.bookingStatus === "CONFIRMED" || row.bookingStatus === "BOARDED";
                    return (
                      <tr key={i} className="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                        <td className="px-4 py-3 font-mono font-semibold whitespace-nowrap">{row.bookingRef}</td>
                        <td className="px-4 py-3 whitespace-nowrap">{row.passengerName}</td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs text-muted-foreground">{row.passengerCategory}</td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs">
                          <span className="font-medium">{row.seatClassName ?? "—"}</span>
                          {row.coachNumber && <span className="text-muted-foreground"> · {row.coachNumber}</span>}
                          {row.seatNumber && <span className="text-muted-foreground"> · #{row.seatNumber}</span>}
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap tabular-nums">
                          {formatCurrency(row.fareMinor, row.currency)}
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap">
                          <Badge variant="status" status={isPaid ? "PAID" : row.paymentStatus}>
                            {isPaid ? "PAID" : row.paymentStatus}
                          </Badge>
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs text-muted-foreground">
                          {row.bookedAt ? formatDateTime(row.bookedAt) : "—"}
                        </td>
                      </tr>
                    );
                  })}
                  {pagedSeats.length === 0 && (
                    <tr>
                      <td colSpan={7} className="py-8 text-center text-sm text-muted-foreground">
                        No seats found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
            <Pagination currentPage={seatsPage} totalPages={seatsTotalPages} onPageChange={setSeatsPage} />
          </div>}

          {/* Blocked Seats Tab */}
          {tab === "blocked" && (
            <div className="card p-0">
              <div className="px-4 pt-4 pb-3">
                <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
                  Blocked Seats
                </h3>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 dark:bg-gray-800">
                    <tr>
                      {["Seat Class · Coach · Seat", "Reason", "Blocked By", "Blocked At", "Unblock At"].map((h) => (
                        <th key={h} className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400 whitespace-nowrap">
                          {h}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                    {pagedBlocked.length === 0 && (
                      <tr>
                        <td colSpan={5} className="py-8 text-center text-sm text-muted-foreground">No blocked seats</td>
                      </tr>
                    )}
                    {pagedBlocked.map((b) => (
                      <tr key={b.id} className="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                        <td className="px-4 py-3 whitespace-nowrap text-xs">
                          <span className="font-medium">{b.seatClassName ?? "—"}</span>
                          {b.coachNumber && <span className="text-muted-foreground"> · {b.coachNumber}</span>}
                          {b.seatNumber && <span className="text-muted-foreground"> · #{b.seatNumber}</span>}
                        </td>
                        <td className="px-4 py-3 text-xs text-muted-foreground max-w-xs truncate" title={b.reason}>
                          {b.reason}
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs">{b.blockedBy}</td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs text-muted-foreground">
                          {formatDateTime(b.blockedAt)}
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-xs text-muted-foreground">
                          {b.unblockAt ? formatDateTime(b.unblockAt) : "—"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pagination currentPage={blockedPage} totalPages={blockedTotalPages} onPageChange={setBlockedPage} />
            </div>
          )}
        </>
      )}

      {!data && !isLoading && scheduleId && (
        <div className="card py-12 text-center text-muted-foreground">
          No data found for this schedule.
        </div>
      )}
    </div>
  );
}
