'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { ChevronUp, Save } from 'lucide-react';
import Link from 'next/link';
import { useState, type ReactNode } from 'react';

import { PageHeader } from '@/components/layout/page-header';
import { placeOf, SummarySidebar, type Place } from '@/components/shipments/summary-sidebar';
import { Button } from '@/components/ui/button';
import { Drawer } from '@/components/ui/overlay';
import { countryName, flagEmoji } from '@/lib/format';
import { formatMoney } from '@/lib/money';
import type { ShipmentDraft } from '@/lib/wizard';

/** Slides step content 16px in the direction of travel and fades it, 220ms. */
export function StepTransition({ step, children }: { step: number; children: ReactNode }) {
  const reduce = useReducedMotion();
  const [state, setState] = useState({ step, direction: 1 });
  if (state.step !== step) setState({ step, direction: step > state.step ? 1 : -1 });
  const offset = reduce ? 0 : 16 * state.direction;
  return (
    <AnimatePresence mode="wait" initial={false} custom={state.direction}>
      <motion.div
        key={step}
        initial={{ opacity: 0, x: offset }}
        animate={{ opacity: 1, x: 0 }}
        exit={{ opacity: 0, x: -offset }}
        transition={{ duration: 0.22, ease: [0.2, 0.8, 0.2, 1] }}
      >
        {children}
      </motion.div>
    </AnimatePresence>
  );
}

const shortPlace = (place: Place | null): string => {
  if (place === null) return '—';
  return `${flagEmoji(place.countryCode)} ${place.city.length > 0 ? place.city : countryName(place.countryCode)}`.trim();
};

export function WizardFrame({
  draft,
  sender,
  recipient,
  international,
  balanceMinor,
  currency,
  summaryOpen,
  onToggleSummary,
  onSaveDraft,
  back,
  primary,
  children,
}: {
  draft: ShipmentDraft;
  sender?: Place | null;
  recipient?: Place | null;
  international: boolean;
  balanceMinor?: number;
  currency: string;
  summaryOpen: boolean;
  onToggleSummary: (open: boolean) => void;
  onSaveDraft: () => void;
  /** Left side of the action bar (Back). */
  back: ReactNode;
  /** Right side of the action bar (Continue / Confirm). */
  primary: ReactNode;
  children: ReactNode;
}) {
  const from = placeOf(draft.sender, sender);
  const to = placeOf(draft.recipient, recipient);
  const quote = draft.selectedQuote;
  const summary = (
    <SummarySidebar draft={draft} sender={sender} recipient={recipient} international={international} balanceMinor={balanceMinor} currency={currency} />
  );

  return (
    <>
      <PageHeader
        title="Create shipment"
        description="Add the addresses and parcel, compare couriers and buy a label."
        breadcrumb="Shipments / New"
        actions={
          <>
            <Button type="button" variant="ghost" onClick={onSaveDraft}>
              <Save className="h-4 w-4" aria-hidden="true" />
              Save draft
            </Button>
            {/* The wizard's leave-confirmation intercepts this link while the draft has changes. */}
            <Link href="/shipments" className="inline-flex h-10 items-center rounded-md px-3 text-small font-semibold text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
              Cancel
            </Link>
          </>
        }
      />

      <div className="grid gap-6 pb-36 lg:grid-cols-3 lg:pb-0">
        <div className="grid min-w-0 content-start gap-6 lg:col-span-2">
          {children}
          {/* Action bar: inline on desktop, sticky above the summary bar on mobile */}
          <div className="sticky bottom-[68px] z-20 -mx-4 flex items-center justify-between gap-3 border-t border-border bg-background/90 px-4 py-3 backdrop-blur-[12px] lg:static lg:mx-0 lg:border-0 lg:bg-transparent lg:px-0 lg:py-0 lg:backdrop-blur-none">
            <div>{back}</div>
            <div className="flex items-center gap-2">{primary}</div>
          </div>
        </div>
        <div className="hidden lg:block">
          <div className="sticky top-24">{summary}</div>
        </div>
      </div>

      {/* Mobile summary bar */}
      <div className="fixed inset-x-0 bottom-0 z-30 border-t border-border bg-surface/95 px-4 py-3 shadow-lg backdrop-blur-[12px] lg:hidden">
        <button
          type="button"
          className="flex w-full items-center justify-between gap-3 text-left"
          aria-haspopup="dialog"
          onClick={() => onToggleSummary(true)}
        >
          <span className="min-w-0">
            <span className="block text-caption text-muted-foreground">Summary</span>
            <span className="block truncate text-small font-semibold">
              {shortPlace(from)} <span className="text-subtle-foreground">→</span> {shortPlace(to)}
            </span>
          </span>
          <span className="flex shrink-0 items-center gap-2">
            <span className="font-display text-h3 font-extrabold tabular-nums">{quote === null ? '—' : formatMoney(quote.totalMinor, quote.currency)}</span>
            <ChevronUp className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
          </span>
        </button>
      </div>
      <Drawer open={summaryOpen} title="Shipment summary" side="bottom" onClose={() => onToggleSummary(false)} className="px-3 pb-6">
        {summary}
      </Drawer>
    </>
  );
}
