'use client';

import { useState } from 'react';
import {
  CONTINUE_LABEL,
  REQUEST_APPROVAL_PENDING_LABEL,
} from '@/services/flights/approvalRequest';
import type { FlightData } from './types';
import FlightNumbers from './FlightNumbers';
import AirlineLogo from './AirlineLogo';

interface MultiCityStickyBarProps {
  selectedLegs: (FlightData | null)[];
  activeLeg: number;
  totalLegs: number;
  onNext: () => void;
  onContinue: () => void;
  /** Optional per-leg copy for the "not selected yet" placeholder, e.g. round
   *  trip passes ["Outbound", "Return"] instead of the generic "leg N" label. */
  legLabels?: string[];
  /** True while onContinue is mid-flight (e.g. skipping straight to review
   *  when every leg has only one fare option) — blocks a second click and
   *  swaps the label rather than disabling, since this is an `<a>`, not a
   *  real `<button>`. */
  continuing?: boolean;
}

type FareTab = 'fare-details' | 'fare-breakup';

export default function MultiCityStickyBar({
  selectedLegs,
  activeLeg,
  totalLegs,
  onNext,
  onContinue,
  legLabels,
  continuing = false,
}: MultiCityStickyBarProps) {
  const [isFareDetailsOpen, setIsFareDetailsOpen] = useState(false);
  const [activeTab, setActiveTab] = useState<FareTab>('fare-details');

  const isVisible = selectedLegs.some((l) => l !== null);
  const currency = selectedLegs.find((l) => l !== null)?.currency ?? '$';

  // Mirrors the skip-the-modal check the parent's onContinue makes: when
  // every chosen leg has exactly one fare there is nothing to pick, so this
  // goes straight to the approval request instead of opening the fares modal —
  // "Request approval" says that up front. (leisure-ui booked here instead.)
  const chosenLegs = selectedLegs.filter((l): l is FlightData => l !== null);
  const isBookNow = chosenLegs.length > 0 && chosenLegs.every((l) => (l.fareOptions?.length ?? 0) === 1);

  const totalBase = selectedLegs.reduce((acc, l) => acc + (l?.pricePerPerson ?? 0), 0);
  const totalSurcharges = selectedLegs.reduce((acc, l) => acc + (l?.taxes ?? 0), 0);
  const totalPrice = totalBase + totalSurcharges;

  if (!isVisible) return null;

  return (
    <div className="round-trip-sticky-bar js-sticky-bar show" aria-hidden="false">
      <div className="container webNewContent">
        <div
          className={`round-trip-sticky-shell shadow-lg js-sticky-shell flex-column${
            !isFareDetailsOpen ? ' is-collapsed' : ''
          }`}
        >

          <div className="d-flex align-items-center justify-content-between gap-3 w-100">
            <div className="round-trip-sticky-items js-sticky-items overflow-auto">

              {selectedLegs.map((legFlight, i) => {
                const leg = legFlight?.outbound ?? null;
                return (
                  <div key={i} className="round-trip-sticky-item">
                    {leg ? (
                      <div className="d-flex align-items-start gap-3">
                        { }
                        <AirlineLogo code={leg.airline.code} name={leg.airline.name} className="round-trip-sticky-logo" />
                        <div className="min-w-0">
                          <div className="round-trip-sticky-route d-flex flex-column">
                            <span className="color-text-black fw-600 text-sm">{leg.departure.airport}</span>
                            <span className="color-text-black fw-600 text-sm">{leg.arrival.airport}</span>
                          </div>
                          <div className="round-trip-sticky-fare">
                            {currency}{legFlight?.pricePerPerson}
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="d-flex align-items-start gap-3">
                        <div className="min-w-0">
                          <div className="round-trip-sticky-route d-flex flex-column">
                            <span className="text-xs flight-detail-label">Select {legLabels?.[i] ?? `leg ${i + 1}`} flight</span>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}

            </div>

            <div className="round-trip-sticky-summary ms-auto">
              <div className="round-trip-sticky-total">
                <small className="text-xs d-block color-content opacity-75 fw-600">Trip total</small>
                <div className="mainHeading color-text-black fw-bold mb-0 js-sticky-total">
                  {currency}{totalPrice}
                </div>
                <small
                  className="text-xs d-block color-text-second fw-600 cursor-pointer"
                  onClick={() => setIsFareDetailsOpen((v) => !v)}
                >
                  Fare Details
                </small>
              </div>
              <div className="d-flex align-items-center gap-2 gap-sm-3">
                {activeLeg < totalLegs - 1 ? (
                  <a
                    className="buttons btnColor-second color-text-white-same rounded-3 px-3 py-2 text-sm fw-500"
                    role="button"
                    onClick={onNext}
                  >
                    Next Flight
                  </a>
                ) : (
                  <a
                    className="buttons btnColor-second color-text-white-same rounded-3 px-3 py-2 text-sm fw-500"
                    role="button"
                    aria-disabled={continuing}
                    onClick={() => {
                      if (!continuing) onContinue();
                    }}
                  >
                    {continuing
                      ? REQUEST_APPROVAL_PENDING_LABEL
                      : isBookNow
                        ? CONTINUE_LABEL
                        : 'Continue'}
                  </a>
                )}
                <button
                  type="button"
                  className="round-trip-sticky-toggle no-bg-btn js-sticky-toggle"
                  aria-expanded={isFareDetailsOpen}
                  aria-controls="multiCityStickyItems"
                  onClick={() => setIsFareDetailsOpen((v) => !v)}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width={24}
                    height={24}
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={2}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="iconSize-20 stroke-content"
                  >
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <div
            className={`collapse position-relative z-1 w-100 fare-details-section${isFareDetailsOpen ? ' show' : ''}`}
            id="multiCityFareDetailsInfo"
          >
            <div className="card card-body">
              <div
                className="nav nav-pills flight-legs-tabs gap-2 mb-3 flex-nowrap overflow-auto"
                id="mcStickyNav"
                role="tablist"
              >
                <button
                  className={`nav-link w-250 border border-2 bgColor-white rounded-3 p-2 text-center d-flex flex-column gap-1${activeTab === 'fare-details' ? ' active' : ''}`}
                  type="button"
                  role="tab"
                  aria-selected={activeTab === 'fare-details'}
                  onClick={() => setActiveTab('fare-details')}
                >
                  <span className="text-sm fw-500 color-text-dark">Fare Details</span>
                </button>
                <button
                  className={`nav-link w-250 border border-2 bgColor-white rounded-3 p-2 text-center d-flex flex-column gap-1${activeTab === 'fare-breakup' ? ' active' : ''}`}
                  type="button"
                  role="tab"
                  aria-selected={activeTab === 'fare-breakup'}
                  tabIndex={activeTab === 'fare-breakup' ? 0 : -1}
                  onClick={() => setActiveTab('fare-breakup')}
                >
                  <span className="text-sm fw-500 color-text-dark">Fare Summary</span>
                </button>
              </div>

              <div className="tab-content" id="mcStickyContent">

                {/* ——— Fare Details tab ——— */}
                <div
                  className={`tab-pane fade${activeTab === 'fare-details' ? ' active show' : ''}`}
                  id="mc-fare-details"
                  role="tabpanel"
                >
                  <div className="container">
                    <div className="row g-md-2 g-4">
                      {selectedLegs.map((legFlight, i) => {
                        const leg = legFlight?.outbound ?? null;
                        return (
                          <div key={i} className="col-md-6">
                            <div className="d-flex flex-column gap-3">
                              <div className="card rounded-start-3 w-100 bgColor-white p-3 m-0">
                                {leg ? (
                                  <div className="row listing-row g-0 h-100">
                                    <div className="col-md-12">
                                      <div className="row">
                                        <div className="col-xxl-2 text-center col-xl-2 ps-0 col-lg-2 col-md-2 col-sm-12 col-12 h-100 pt-2 pe-md-0 d-flex flex-wrap d-md-block order-1 order-md-1">
                                          <div className="flight-view ps-2 ps-sm-0">
                                            { }
                                            <AirlineLogo code={leg.airline.code} name={leg.airline.name} className="flight-airline-logo" />
                                            <div className="flight-details text-start text-md-center xs-2">
                                              <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0 mt-2">
                                                {leg.airline.name}
                                              </div>
                                              <FlightNumbers numbers={leg.airline.flightNumbers ?? [leg.airline.flightNumber]} />
                                            </div>
                                          </div>
                                          <div className="flight-starting-price d-block d-sm-none ms-auto text-end">
                                            <div className="listing-div text-end d-flex flex-column align-items-end">
                                              <small className="d-block mb-2 text-xs">from</small>
                                              <h5 className="mb-0">
                                                <span className="mainHeading color-text-dark fw-bold">
                                                  {currency}{legFlight?.pricePerPerson}
                                                </span>
                                              </h5>
                                              <small className="d-block color-text-dark text-xs mb-md-2">per adult</small>
                                            </div>
                                          </div>
                                        </div>
                                        <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-10 col-sm-12 col-12 h-100 booking-content-details p-0 pe-md-5 order-2 order-md-2">
                                          <div className="flight-routes d-flex flex-wrap flex-md-nowrap align-items-center border-bottom pb-3">
                                            <div className="flex-grow-1 px-3 w-s-100 order-md-2">
                                              <div className="flight-path position-relative w-100">
                                                <div className="path-line"></div>
                                                <span className="path-dot dot-start bg-white"></span>
                                                <span className="path-dot dot-end"></span>
                                                <span className="plane bgColor-white px-1 me-2">
                                                  <svg
                                                    xmlns="http://www.w3.org/2000/svg"
                                                    width={16}
                                                    height={16}
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeWidth={2}
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                  >
                                                    <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
                                                  </svg>
                                                </span>
                                              </div>
                                              <div className="time text-center">
                                                <span className="text-xs text-grey me-2">{leg.duration}</span>
                                                <span className={`text-xs px-2 py-1 rounded-5 ${leg.stops === 0 ? 'non-stop' : leg.stops === 1 ? 'one-stop' : 'multi-stop'}`}>
                                                  {leg.stops === 0 ? 'Non-stop' : leg.stops === 1 ? '1 Stop' : `${leg.stops} Stops`}
                                                </span>
                                              </div>
                                            </div>
                                            <div className="w-s-50 order-md-1 pe-sm-1 ps-2 ps-sm-0">
                                              <div className="color-text-dark font-inter fw-bolder text-xl">{leg.departure.time}</div>
                                              <div className="color-text-black fw-normal font-inter text-sm">{leg.departure.airport}</div>
                                              <div className="flight-detail-label text-sm">{leg.departure.city}</div>
                                            </div>
                                            <div className="w-s-50 text-end order-md-3">
                                              <div className="color-text-dark font-inter fw-bolder text-xl">{leg.arrival.time}</div>
                                              <div className="color-text-black text-sm">{leg.arrival.airport}</div>
                                              <div className="flight-detail-label text-sm">{leg.arrival.city}</div>
                                            </div>
                                          </div>
                                          <div className="d-md-flex justify-content-between align-items-center gap-2">
                                            <div className="flight-features pt-3 d-flex flex-wrap align-items-center gap-2 ps-2 ps-sm-0">
                                              {leg.cabin && (
                                                <div className="cabin text-sm text-grey">
                                                  <svg xmlns="http://www.w3.org/2000/svg" width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400">
                                                    <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                                                    <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                                                    <path d="M10 20h4" /><circle cx={16} cy={20} r={2} /><circle cx={8} cy={20} r={2} />
                                                  </svg> {" "}
                                                  Cabin: {leg.cabin}
                                                </div>
                                              )}
                                              {leg.checkin && (
                                                <div className="checkin text-sm text-grey">
                                                  <svg xmlns="http://www.w3.org/2000/svg" width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400">
                                                    <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                                                    <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                                                    <path d="M10 20h4" /><circle cx={16} cy={20} r={2} /><circle cx={8} cy={20} r={2} />
                                                  </svg> {" "}
                                                  Check-in: {leg.checkin}
                                                </div>
                                              )}
                                            </div>
                                            <div className="listing-div text-end d-none d-sm-block pe-md-2">
                                              <small className="d-block mb-2 text-xs">from</small>
                                              <h5 className="mb-0">
                                                <span className="mainHeading color-text-dark fw-bold">
                                                  {currency}{legFlight?.pricePerPerson}
                                                </span>
                                              </h5>
                                              <small className="d-block color-text-dark text-xs mb-md-2">per adult</small>
                                            </div>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                ) : (
                                  <div className="text-xs flight-detail-label">No flight selected for leg {i + 1}</div>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>

                {/* ——— Fare Breakup tab ——— */}
                <div
                  className={`tab-pane fade${activeTab === 'fare-breakup' ? ' active show' : ''}`}
                  id="mc-fare-breakup"
                  role="tabpanel"
                >
                  <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0 mb-2">
                    Fare Breakup
                  </div>
                  <div className="table-responsive">
                    <table className="table table-bordered align-middle mb-2">
                      <thead>
                        <tr className="border-bottom">
                          <th className="text-sm fw-500 py-2">Leg</th>
                          <th className="text-sm fw-500 py-2">Base Fare</th>
                          <th className="text-sm fw-500 py-2">Surcharges</th>
                          <th className="text-sm fw-500 py-2">Total</th>
                        </tr>
                      </thead>
                      <tbody>
                        {selectedLegs.map((legFlight, i) => {
                          const leg = legFlight?.outbound ?? null;
                          return (
                            <tr key={i} className="border-bottom">
                              <td className="text-sm py-2">
                                {leg
                                  ? `${leg.departure.airport} - ${leg.arrival.airport}`
                                  : `Leg ${i + 1}`}
                              </td>
                              <td className="text-sm py-2">{currency}{legFlight?.pricePerPerson ?? 0}</td>
                              <td className="text-sm py-2">{currency}{legFlight?.taxes ?? 0}</td>
                              <td className="text-sm py-2">
                                {currency}{(legFlight?.pricePerPerson ?? 0) + (legFlight?.taxes ?? 0)}
                              </td>
                            </tr>
                          );
                        })}
                        <tr>
                          <td className="text-sm py-2 fw-600 border-bottom-0">Grand Total</td>
                          <td className="text-sm py-2 fw-600 border-bottom-0">{currency}{totalBase}</td>
                          <td className="text-sm py-2 fw-600 border-bottom-0">{currency}{totalSurcharges}</td>
                          <td className="text-sm py-2 fw-600 border-bottom-0">{currency}{totalPrice}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
