'use client';

import { useEffect } from 'react';

import Drawer from '@/components/ui/Drawer';
import { isLayoverAvailable } from '@/services/flights/layoverAirport.client';
import { layoverChipParts, type LayoverDrawerContext } from '@/services/flights/layoverDisplay';
import TravellerImpressionsCard from '@/components/flights/travellerImpressions/TravellerImpressionsCard';
import { useTravellerImpressions } from '@/services/flights/travellerImpressions/useTravellerImpressions';
import LayoverDrawerSkeleton from './LayoverDrawerSkeleton';
import LayoverGoodToKnow from './LayoverGoodToKnow';
import LayoverHero from './LayoverHero';
import LayoverRatingCard from './LayoverRatingCard';
import LayoverReviewList from './LayoverReviewList';
import { useLayoverAirport } from './useLayoverAirport';
import { noteLayoverAvailability } from './useLayoverAvailability';
import './layover-drawer.css';

/**
 * The layover-airport drawer.
 *
 * Its own chunk, mounted only while open (see KnowYourLayoverLink), so a
 * results page nobody asks a layover question on pays nothing for it.
 *
 * Three terminal states, kept distinct on purpose:
 *   loading      skeletons — the panel and its trip chip are on screen from the
 *                first frame, so the <300ms budget is met by the frame, not by
 *                the request
 *   unavailable  a plain statement. The entry link hides itself from here on,
 *                but whoever is already looking at the panel gets an answer
 *   error        the service or Google failed — offer a retry rather than imply
 *                the airport has no page
 */

function LayoverTripChip({ layover }: { layover: LayoverDrawerContext }) {
  return (
    <div className="layover-chip">
      <span className="layover-chip__lead">Your layover: {layover.duration}</span>
      {layoverChipParts(layover).map((part) => (
        <span key={part} className="layover-chip__part">
          {part}
        </span>
      ))}
    </div>
  );
}

export interface LayoverAirportDrawerProps {
  iataCode: string;
  /**
   * The traveller's own stop. Null when the drawer was opened from a URL rather
   * than a click — a shared link, or Back onto an entry whose trip we no longer
   * hold. The chip is then omitted rather than guessed at: we know which
   * airport, not which stop.
   */
  layover: LayoverDrawerContext | null;
  isOpen: boolean;
  onClose: () => void;
}

export default function LayoverAirportDrawer({ iataCode, layover, isOpen, onClose }: LayoverAirportDrawerProps) {
  const { data, isPending, isError, refetch, isFetching } = useLayoverAirport(iataCode, isOpen);
  const summary = isLayoverAvailable(data) ? data : null;

  // LEIS-928's AI summary of what travellers say about this airport. It is a
  // separate service from the Google-backed rating and reviews below it — a
  // model asked to summarise, not our own aggregate — and it hides itself
  // entirely when it has nothing real to say, so it needs no gate here.
  const impressions = useTravellerImpressions(iataCode, summary?.airport.name);

  // Teach the link what this fetch proved. A definite answer either way beats
  // the batch lookup's cache-only guess, and BAD_IATA/NO_PLACE/NO_CONTENT all
  // mean the same thing to a link: stop offering it.
  //
  // In an effect, not in render: the store notifies its subscribers
  // synchronously, and every layover link on the page is one — updating them
  // from this component's render is the "cannot update a component while
  // rendering a different component" case.
  useEffect(() => {
    if (data) noteLayoverAvailability(iataCode, data.available === true);
  }, [data, iataCode]);

  // The itinerary already knows the airport's name, so the heading is right from
  // the first frame — the panel never opens with a blank title bar.
  const title = `${summary?.airport.name ?? layover?.airport ?? iataCode} (${iataCode})`;
  const subtitle = summary?.airport.formattedAddress ?? summary?.airport.city ?? undefined;

  return (
    <Drawer isOpen={isOpen} onClose={onClose} title={title} subtitle={subtitle} className="layover-drawer">
      {/* Above every branch: it is the one thing on this panel that is about the
          traveller's own trip, and it is known without asking anyone. */}
      {layover && <LayoverTripChip layover={layover} />}

      {isPending && <LayoverDrawerSkeleton />}

      {isError && (
        <div className="p-4 text-center">
          <p className="mb-3 color-text-muted">We couldn&apos;t load information for this airport.</p>
          <button type="button" className="btn btn-outline-secondary" onClick={() => refetch()} disabled={isFetching}>
            {isFetching ? 'Retrying…' : 'Try again'}
          </button>
        </div>
      )}

      {!isPending && !isError && !summary && (
        <div className="p-4">
          <p className="mb-0 color-text-muted">
            We don&apos;t have traveller information for {layover?.airport ?? iataCode} ({iataCode}) yet.
          </p>
        </div>
      )}

      {summary && (
        <>
          <LayoverHero summary={summary} iataCode={iataCode} fallbackName={layover?.airport ?? iataCode} />

          <div className="layover-body">
            {/* Renders nothing until sub-task 3's AI endpoint supplies slides. */}
            <LayoverGoodToKnow slides={[]} />

            {summary.editorialSummary && (
              <section className="layover-card">
                <h4 className="layover-card__title">About this airport</h4>
                <p className="mb-0">{summary.editorialSummary}</p>
              </section>
            )}

            <LayoverRatingCard summary={summary} />

            <TravellerImpressionsCard result={impressions.result} loading={impressions.loading} />

            {/* Hidden entirely when Google holds no readable reviews — the
                ticket's fallback rule, and better than an empty heading. */}
            {summary.reviewCount > 0 && <LayoverReviewList iataCode={iataCode} enabled={isOpen} />}
          </div>
        </>
      )}
    </Drawer>
  );
}
