"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Users, Armchair, BarChart3, Train, Download } from "lucide-react";
import { apiClient } from "@/lib/api-client";
import { formatDateTime } from "@/lib/utils";
import ActionButton from "@/components/ui/ActionButton";
import Pagination from "@/components/ui/Pagination";
import { usePagination } from "@/lib/use-pagination";

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

interface PassengersReport {
  schedule: {
    id: string;
    trainName: string;
    origin: string;
    destination: string;
    departureAt: string;
    arrivalAt: string;
  };
  summary: {
    totalSeats: number;
    totalPassengers: number;
    occupancyRate: number;
  };
  byCoach: {
    coachNumber: string;
    coachType: string;
    totalSeats: number;
    booked: number;
    occupancyRate: number;
  }[];
  byClass: {
    className: string;
    totalSeats: number;
    booked: number;
    occupancyRate: number;
  }[];
  byOrigin: { stationName: string; passengers: number }[];
  byDestination: { stationName: string; passengers: number }[];
}

interface PassengerRow {
  bookingRef: string;
  passengerName: string;
  passengerCategory: string;
  idDocumentType: string | null;
  idDocumentNumber: string | null;
  passportNumber: string | null;
  passportCountry: string | null;
  seatLabel: string | null;
  seatNumber: string | null;
  seatClassName: string | null;
  coachNumber: string | null;
  coachType: string | null;
  nationality: string | null;
  origin: string | null;
  destination: string | null;
  amountPaidMinor: number;
  currency: string;
  isGroupBooking: boolean;
  bookingStatus: string;
}

type Tab = "occupancy" | "list";

export default function PassengersReportPage() {
  const [scheduleId, setScheduleId] = useState("");
  const [tab, setTab] = useState<Tab>("occupancy");
  const [listSearch, setListSearch] = useState("");
  const [filterOrigin, setFilterOrigin] = useState("");
  const [filterSeatClass, setFilterSeatClass] = useState("");
  const [filterCoachNumber, setFilterCoachNumber] = 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<PassengersReport>({
    queryKey: ["passengers-report", scheduleId],
    queryFn: () =>
      apiClient.get(`/reports/passengers?scheduleId=${scheduleId}`),
    enabled: !!scheduleId,
  });

  const { data: passengerList = [], isLoading: listLoading } = useQuery<
    PassengerRow[]
  >({
    queryKey: ["passengers-list", scheduleId],
    queryFn: () =>
      apiClient.get(`/reports/passengers/list?scheduleId=${scheduleId}`),
    enabled: !!scheduleId,
  });

  const coachNumberOptions = [
    ...new Set(passengerList.map((p) => p.coachNumber).filter(Boolean)),
  ].sort() as string[];
  const seatClassOptions = [
    ...new Set(passengerList.map((p) => p.seatClassName).filter(Boolean)),
  ].sort() as string[];
  const originOptions = [
    ...new Set(passengerList.map((p) => p.origin).filter(Boolean)),
  ].sort() as string[];

  const filteredList = passengerList
    .filter((p) => {
      if (filterCoachNumber && p.coachNumber !== filterCoachNumber) return false;
      if (filterOrigin && p.origin !== filterOrigin) return false;
      if (filterSeatClass && p.seatClassName !== filterSeatClass) return false;
      if (listSearch.trim()) {
        const q = listSearch.toLowerCase();
        return (
          p.passengerName.toLowerCase().includes(q) ||
          p.bookingRef.toLowerCase().includes(q) ||
          (p.idDocumentNumber ?? "").toLowerCase().includes(q) ||
          (p.passportNumber ?? "").toLowerCase().includes(q)
        );
      }
      return true;
    })
    .sort((a, b) => a.bookingRef.localeCompare(b.bookingRef));

  const { paged: pagedList, page: listPage, totalPages: listTotalPages, setPage: setListPage, reset: resetListPage } = usePagination(filteredList, 50);

  const downloadCsv = (csv: string, filename: string) => {
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  const doExportOccupancy = () => {
    if (!data) return;
    const rows = data.byCoach.map((c) => [
      c.coachNumber,
      c.coachType,
      String(c.totalSeats),
      String(c.booked),
      `${c.occupancyRate}%`,
    ]);
    downloadCsv(
      [
        ["Coach", "Type", "Total Seats", "Booked", "Occupancy"].join(","),
        ...rows.map((r) => r.join(",")),
      ].join("\n"),
      `occupancy-${scheduleId}.csv`,
    );
  };

  const doExportList = () => {
    if (!filteredList.length) return;
    const headers = ['Name', 'Nationality', 'Passport Number', 'Seat Class', 'Coach', 'Seat', 'Origin', 'Destination', 'Amount Paid (ETB)', 'Booking Ref'];
    const rows = filteredList.map((p) =>
      [
        p.passengerName,
        p.nationality ?? '—',
        p.passportNumber ?? '—',
        p.seatClassName ?? '—',
        p.coachNumber ?? '—',
        p.seatNumber ?? '—',
        p.origin ?? '—',
        p.destination ?? '—',
        (p.amountPaidMinor / 100).toFixed(2),
        p.bookingRef,
      ].map((v) => `"${String(v).replace(/"/g, '""')}"`),
    );
    downloadCsv(
      [headers.join(','), ...rows.map((r) => r.join(','))].join('\n'),
      `passengers-${scheduleId}.csv`,
    );
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">
          Passengers Report
        </h1>
        <p className="text-muted-foreground mt-1">
          Occupancy and passenger breakdown 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("occupancy");
                setListSearch("");
                setFilterCoachNumber("");
                setFilterOrigin("");
                setFilterSeatClass("");
              }}
              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>
          {data && tab === "occupancy" && (
            <ActionButton
              icon={Download}
              variant="secondary"
              onClick={doExportOccupancy}
            >
              Export CSV
            </ActionButton>
          )}
        </div>
        {(isLoading || listLoading) && (
          <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>

      {data && (
        <>
          {/* Schedule info */}
          <div className="card flex items-center gap-4">
            <div className="rounded-lg bg-emerald-100 dark:bg-emerald-900/30 p-2.5">
              <Train className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div>
              <p className="font-semibold">{data.schedule.trainName}</p>
              <p className="text-sm text-muted-foreground">
                {data.schedule.origin} → {data.schedule.destination} ·
                Departure: {formatDateTime(data.schedule.departureAt)}
              </p>
            </div>
          </div>

          {/* Tabs */}
          <div className="border-b border-border flex">
            <button
              onClick={() => setTab("occupancy")}
              className={`px-5 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === "occupancy" ? "border-emerald-500 text-emerald-600 dark:text-emerald-400" : "border-transparent text-muted-foreground hover:text-foreground"}`}
            >
              Occupancy
            </button>
            <button
              onClick={() => setTab("list")}
              className={`px-5 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === "list" ? "border-emerald-500 text-emerald-600 dark:text-emerald-400" : "border-transparent text-muted-foreground hover:text-foreground"}`}
            >
              Passenger List
              {passengerList.length > 0 ? ` (${passengerList.length})` : ""}
            </button>
          </div>

          {/* Occupancy tab */}
          {tab === "occupancy" && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="card flex flex-col gap-1">
                  <div className="flex items-center justify-between">
                    <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                      Total Seats
                    </p>
                    <div className="rounded-lg bg-blue-100 dark:bg-blue-900/30 p-1.5">
                      <Armchair className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                    </div>
                  </div>
                  <p className="text-2xl font-bold tabular-nums mt-1">
                    {data.summary.totalSeats}
                  </p>
                </div>
                <div className="card flex flex-col gap-1">
                  <div className="flex items-center justify-between">
                    <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                      Passengers
                    </p>
                    <div className="rounded-lg bg-emerald-100 dark:bg-emerald-900/30 p-1.5">
                      <Users className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                    </div>
                  </div>
                  <p className="text-2xl font-bold tabular-nums mt-1">
                    {data.summary.totalPassengers}
                  </p>
                </div>
                <div className="card flex flex-col gap-1">
                  <div className="flex items-center justify-between">
                    <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                      Occupancy Rate
                    </p>
                    <div className="rounded-lg bg-purple-100 dark:bg-purple-900/30 p-1.5">
                      <BarChart3 className="h-4 w-4 text-purple-600 dark:text-purple-400" />
                    </div>
                  </div>
                  <p className="text-2xl font-bold tabular-nums mt-1">
                    {data.summary.occupancyRate}%
                  </p>
                  <div className="w-full bg-muted rounded-full h-1.5 mt-1">
                    <div
                      className="bg-purple-500 h-1.5 rounded-full"
                      style={{ width: `${data.summary.occupancyRate}%` }}
                    />
                  </div>
                </div>
              </div>

              <div className="card">
                <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                  By Coach
                </h3>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border text-left text-xs text-muted-foreground uppercase tracking-wider">
                        <th className="pb-2 pr-4">Coach</th>
                        <th className="pb-2 pr-4">Type</th>
                        <th className="pb-2 pr-4 text-right">Seats</th>
                        <th className="pb-2 pr-4 text-right">Booked</th>
                        <th className="pb-2">Occupancy</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {data.byCoach.map((c) => (
                        <tr key={c.coachNumber} className="hover:bg-muted/30">
                          <td className="py-2 pr-4 font-semibold">
                            {c.coachNumber}
                          </td>
                          <td className="py-2 pr-4 text-muted-foreground">
                            {c.coachType}
                          </td>
                          <td className="py-2 pr-4 text-right tabular-nums">
                            {c.totalSeats}
                          </td>
                          <td className="py-2 pr-4 text-right tabular-nums">
                            {c.booked}
                          </td>
                          <td className="py-2">
                            <div className="flex items-center gap-2">
                              <div className="flex-1 bg-muted rounded-full h-1.5">
                                <div
                                  className="bg-emerald-500 h-1.5 rounded-full"
                                  style={{ width: `${c.occupancyRate}%` }}
                                />
                              </div>
                              <span className="tabular-nums text-xs w-10 text-right">
                                {c.occupancyRate}%
                              </span>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="card">
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                    By Class
                  </h3>
                  <div className="space-y-3">
                    {data.byClass.map((c) => (
                      <div key={c.className}>
                        <div className="flex justify-between text-sm mb-1">
                          <span className="font-medium">{c.className}</span>
                          <span className="tabular-nums text-muted-foreground">
                            {c.booked}/{c.totalSeats}
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="flex-1 bg-muted rounded-full h-1.5">
                            <div
                              className="bg-blue-500 h-1.5 rounded-full"
                              style={{ width: `${c.occupancyRate}%` }}
                            />
                          </div>
                          <span className="text-xs tabular-nums w-10 text-right">
                            {c.occupancyRate}%
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="card">
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                    By Boarding Station
                  </h3>
                  <div className="space-y-2">
                    {data.byOrigin.map((o) => (
                      <div
                        key={o.stationName}
                        className="flex justify-between text-sm"
                      >
                        <span className="text-muted-foreground truncate">
                          {o.stationName}
                        </span>
                        <span className="font-semibold tabular-nums ml-2">
                          {o.passengers}
                        </span>
                      </div>
                    ))}
                    {data.byOrigin.length === 0 && (
                      <p className="text-xs text-muted-foreground">No data</p>
                    )}
                  </div>
                </div>
                <div className="card">
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                    By Alighting Station
                  </h3>
                  <div className="space-y-2">
                    {data.byDestination.map((d) => (
                      <div
                        key={d.stationName}
                        className="flex justify-between text-sm"
                      >
                        <span className="text-muted-foreground truncate">
                          {d.stationName}
                        </span>
                        <span className="font-semibold tabular-nums ml-2">
                          {d.passengers}
                        </span>
                      </div>
                    ))}
                    {data.byDestination.length === 0 && (
                      <p className="text-xs text-muted-foreground">No data</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Passenger List tab */}
          {tab === "list" && (
            <div className="space-y-4">
              <div className="flex items-center gap-3 flex-wrap">
                <input
                  type="text"
                  className="input max-w-sm flex-1"
                  placeholder="Search by name or booking ref…"
                  value={listSearch}
                  onChange={(e) => { setListSearch(e.target.value); resetListPage(); }}
                />
                <select
                  className="input w-40"
                  value={filterSeatClass}
                  onChange={(e) => { setFilterSeatClass(e.target.value); resetListPage(); }}
                >
                  <option value="">All classes</option>
                  {seatClassOptions.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
                <select
                  className="input w-36"
                  value={filterCoachNumber}
                  onChange={(e) => { setFilterCoachNumber(e.target.value); resetListPage(); }}
                >
                  <option value="">All coaches</option>
                  {coachNumberOptions.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
                <select
                  className="input w-36"
                  value={filterOrigin}
                  onChange={(e) => { setFilterOrigin(e.target.value); resetListPage(); }}
                >
                  <option value="">All origins</option>
                  {originOptions.map((o) => (
                    <option key={o} value={o}>
                      {o}
                    </option>
                  ))}
                </select>
                {passengerList.length > 0 && (
                  <ActionButton
                    icon={Download}
                    variant="secondary"
                    onClick={doExportList}
                  >
                    Export CSV
                  </ActionButton>
                )}
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border text-left text-xs text-muted-foreground uppercase tracking-wider">
                      <th className="pb-2 pr-4 whitespace-nowrap">Name</th>
                      <th className="pb-2 pr-4 whitespace-nowrap">Nationality</th>
                      <th className="pb-2 pr-4 whitespace-nowrap">Seat Class · Coach · Seat</th>
                      <th className="pb-2 pr-4 whitespace-nowrap">Route</th>
                      <th className="pb-2 pr-4 whitespace-nowrap">Amount Paid</th>
                      <th className="pb-2 whitespace-nowrap">Booking Ref</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {pagedList.map((p, i) => (
                      <tr key={`${p.bookingRef}-${i}`} className="hover:bg-muted/30">
                        <td className="py-2 pr-4 font-medium whitespace-nowrap">{p.passengerName}</td>
                        <td className="py-2 pr-4 text-xs">
                          <span className="text-muted-foreground">{p.nationality ?? '—'}</span>
                          {p.passportNumber && (
                            <span className="ml-1.5 font-mono text-foreground">{p.passportNumber}</span>
                          )}
                        </td>
                        <td className="py-2 pr-4 text-xs">
                          <span className="font-medium">{p.seatClassName ?? '—'}</span>
                          {p.coachNumber && <span className="text-muted-foreground"> · {p.coachNumber}</span>}
                          {p.seatNumber && <span className="text-muted-foreground"> · #{p.seatNumber}</span>}
                        </td>
                        <td className="py-2 pr-4 text-xs text-muted-foreground whitespace-nowrap">
                          {p.origin && p.destination ? `${p.origin} → ${p.destination}` : (p.origin ?? p.destination ?? '—')}
                        </td>
                        <td className="py-2 pr-4 tabular-nums text-xs">
                          {(p.amountPaidMinor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 })} {p.currency}
                        </td>
                        <td className="py-2 font-mono text-xs">{p.bookingRef}</td>
                      </tr>
                    ))}
                    {filteredList.length === 0 && (
                      <tr>
                        <td colSpan={6} className="py-8 text-center text-sm text-muted-foreground">No passengers found</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
              <Pagination currentPage={listPage} totalPages={listTotalPages} onPageChange={setListPage} />
            </div>
          )}
        </>
      )}

      {!data && !isLoading && scheduleId && (
        <div className="card py-12 text-center text-muted-foreground">
          No data found for this schedule.
        </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 occupancy report</p>
        </div>
      )}
    </div>
  );
}
