'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { Check, Lock, MapPin, Package, Search, SlidersHorizontal } from 'lucide-react';
import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react';

import { Container, Section, SectionHeading } from '@/components/layout/container';
import { MockBadge, MockRateRow, MockStatus, MockTimeline, mockRates } from '@/components/marketing/mock-ui';
import { Reveal } from '@/components/motion/reveal';
import { cn } from '@/lib/utils';

const tabs = ['Rates', 'Shipments', 'Tracking'] as const;
type Tab = (typeof tabs)[number];

const bullets = [
  { title: 'Transparent prices', text: 'Every rate shows the full total before you buy.' },
  { title: 'Instant labels', text: 'Print-ready PDF labels the moment you confirm.' },
  { title: 'Clear delivery updates', text: 'One timeline per parcel, from pickup to doorstep.' },
] as const;

const shipments = [
  { id: 'SH-1042', route: 'Berlin → Toronto', courier: 'Priority International', status: 'Label ready', cost: '36.90' },
  { id: 'SH-1041', route: 'Hamburg → Oslo', courier: 'Nordic Parcel', status: 'In transit', cost: '18.40' },
  { id: 'SH-1040', route: 'Munich → Lyon', courier: 'Economy Ground', status: 'Delivered', cost: '12.75' },
  { id: 'SH-1039', route: 'Cologne → Austin', courier: 'Express Air', status: 'Exception', cost: '52.10' },
  { id: 'SH-1038', route: 'Berlin → Madrid', courier: 'Swift Freight', status: 'Cancelled', cost: '15.60' },
] as const;

function RatesScreen() {
  return (
    <div className="grid gap-4 md:grid-cols-[13rem_minmax(0,1fr)]">
      <div className="hidden rounded-lg border border-border bg-surface-muted p-3 md:block">
        <p className="text-[11px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground">Shipment</p>
        <div className="mt-3 grid gap-2.5 text-caption">
          <div>
            <p className="text-subtle-foreground">From</p>
            <p className="font-medium">Berlin, DE</p>
          </div>
          <div>
            <p className="text-subtle-foreground">To</p>
            <p className="font-medium">Toronto, CA</p>
          </div>
          <div>
            <p className="text-subtle-foreground">Parcel</p>
            <p className="font-medium tabular-nums">30 × 20 × 15 cm · 2.4 kg</p>
          </div>
        </div>
      </div>
      <div>
        <div className="mb-3 flex items-center justify-between gap-3">
          <p className="text-small font-semibold">3 services available</p>
          <span className="inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-caption text-muted-foreground">
            <SlidersHorizontal className="h-3 w-3" />
            Sort: price
          </span>
        </div>
        <div className="grid gap-2">
          {mockRates.map((rate) => (
            <MockRateRow key={rate.name} rate={rate} badge={rate.selected ? <MockBadge tone="success">Cheapest</MockBadge> : undefined} />
          ))}
        </div>
        <div className="mt-3 flex justify-end">
          <span className="rounded-md bg-brand-gradient px-3 py-2 text-caption font-semibold text-primary-foreground shadow-sm">Buy label · 36.90</span>
        </div>
      </div>
    </div>
  );
}

function ShipmentsScreen() {
  return (
    <div>
      <div className="mb-3 flex flex-wrap items-center gap-2">
        <span className="inline-flex h-8 flex-1 items-center gap-2 rounded-md border border-border bg-surface px-2.5 text-caption text-subtle-foreground sm:max-w-56">
          <Search className="h-3.5 w-3.5" />
          Search shipments
        </span>
        {['All', 'In transit', 'Delivered'].map((chip, index) => (
          <span
            key={chip}
            className={cn('rounded-pill px-2.5 py-1 text-caption font-semibold', index === 0 ? 'bg-primary-soft text-primary' : 'bg-surface-muted text-muted-foreground')}
          >
            {chip}
          </span>
        ))}
      </div>
      <div className="overflow-hidden rounded-lg border border-border">
        <div className="grid grid-cols-[5rem_minmax(0,1fr)_auto] gap-3 bg-surface-muted px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground sm:grid-cols-[5rem_minmax(0,1fr)_minmax(0,1fr)_7rem_4rem]">
          <span>Shipment</span>
          <span>Route</span>
          <span className="hidden sm:block">Courier</span>
          <span>Status</span>
          <span className="hidden text-right sm:block">Cost</span>
        </div>
        {shipments.map((row) => (
          <div
            key={row.id}
            className="grid grid-cols-[5rem_minmax(0,1fr)_auto] items-center gap-3 border-t border-border px-3 py-2.5 text-caption sm:grid-cols-[5rem_minmax(0,1fr)_minmax(0,1fr)_7rem_4rem]"
          >
            <span className="font-mono font-semibold">{row.id}</span>
            <span className="truncate text-muted-foreground">{row.route}</span>
            <span className="hidden truncate text-muted-foreground sm:block">{row.courier}</span>
            <span>
              <MockStatus status={row.status} />
            </span>
            <span className="hidden text-right font-semibold tabular-nums sm:block">{row.cost}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TrackingScreen() {
  return (
    <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_14rem]">
      <div className="rounded-lg border border-border p-4">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <div>
            <p className="text-[11px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground">Tracking number</p>
            <p className="font-mono text-small font-semibold tracking-wide">SHP10427781DE</p>
          </div>
          <MockStatus status="In transit" />
        </div>
        <div className="mt-4 h-1.5 overflow-hidden rounded-pill bg-surface-muted">
          <div className="h-full w-[62%] rounded-pill bg-brand-gradient" />
        </div>
        <MockTimeline
          className="mt-5"
          currentIndex={3}
          events={[
            { title: 'Label created', meta: 'Berlin, DE · Mon 09:12' },
            { title: 'Picked up', meta: 'Berlin Hub, DE · Mon 16:40' },
            { title: 'Departed facility', meta: 'Frankfurt, DE · Tue 05:22' },
            { title: 'In transit', meta: 'Toronto Gateway, CA · Wed 11:08' },
          ]}
        />
      </div>
      <div className="hidden gap-3 md:grid">
        <div className="rounded-lg border border-border bg-surface-muted p-3">
          <p className="inline-flex items-center gap-1.5 text-caption font-semibold">
            <MapPin className="h-3.5 w-3.5 text-primary" />
            Estimated delivery
          </p>
          <p className="mt-1 font-display text-h3 font-bold">Thu, 14 Nov</p>
        </div>
        <div className="rounded-lg border border-border bg-surface-muted p-3">
          <p className="inline-flex items-center gap-1.5 text-caption font-semibold">
            <Package className="h-3.5 w-3.5 text-primary" />
            Priority International
          </p>
          <p className="mt-1 text-caption text-muted-foreground">2.4 kg · 1 parcel</p>
        </div>
      </div>
    </div>
  );
}

export function ProductShowcase() {
  const reduce = useReducedMotion();
  const baseId = useId();
  const [tab, setTab] = useState<Tab>('Rates');
  const [auto, setAuto] = useState(true);
  const [paused, setPaused] = useState(false);
  const [height, setHeight] = useState<number | 'auto'>('auto');
  const contentRef = useRef<HTMLDivElement>(null);
  const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);

  useEffect(() => {
    if (!auto || paused || reduce) return undefined;
    const timer = window.setTimeout(() => {
      setTab((current) => tabs[(tabs.indexOf(current) + 1) % tabs.length] ?? 'Rates');
    }, 6000);
    return () => window.clearTimeout(timer);
  }, [auto, paused, reduce, tab]);

  useEffect(() => {
    const node = contentRef.current;
    if (node === null) return undefined;
    const observer = new ResizeObserver(() => setHeight(node.offsetHeight));
    observer.observe(node);
    return () => observer.disconnect();
  }, []);

  const select = (next: Tab) => {
    setAuto(false);
    setTab(next);
  };

  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
    let next = index;
    if (event.key === 'ArrowRight') next = (index + 1) % tabs.length;
    else if (event.key === 'ArrowLeft') next = (index - 1 + tabs.length) % tabs.length;
    else if (event.key === 'Home') next = 0;
    else if (event.key === 'End') next = tabs.length - 1;
    else return;
    event.preventDefault();
    const nextTab = tabs[next];
    if (nextTab === undefined) return;
    select(nextTab);
    tabRefs.current[next]?.focus();
  };

  return (
    <Section>
      <Container>
        <Reveal>
          <SectionHeading eyebrow="See it in action" title="Built for fast, confident shipping" text="A quick look at the screens your team will use every day." />
        </Reveal>
        <div onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={() => setPaused(false)}>
          <Reveal index={1}>
            <div role="tablist" aria-label="Product screens" className="mx-auto mt-10 flex w-fit rounded-pill border border-border bg-surface-muted p-1">
              {tabs.map((item, index) => {
                const selected = tab === item;
                return (
                  <button
                    key={item}
                    ref={(node) => {
                      tabRefs.current[index] = node;
                    }}
                    id={`${baseId}-tab-${index}`}
                    type="button"
                    role="tab"
                    aria-selected={selected}
                    aria-controls={`${baseId}-panel`}
                    tabIndex={selected ? 0 : -1}
                    className={cn(
                      'relative min-h-10 rounded-pill px-4 text-small font-semibold transition-colors duration-180 sm:px-5',
                      selected ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
                    )}
                    onClick={() => select(item)}
                    onKeyDown={(event) => onKeyDown(event, index)}
                  >
                    {selected ? (
                      <motion.span
                        layoutId={`${baseId}-thumb`}
                        className="absolute inset-0 rounded-pill bg-surface shadow-sm"
                        transition={reduce ? { duration: 0 } : { type: 'spring', stiffness: 420, damping: 34 }}
                      />
                    ) : null}
                    <span className="relative">{item}</span>
                  </button>
                );
              })}
            </div>
          </Reveal>
          <Reveal index={2}>
            <div className="mx-auto mt-6 max-w-4xl overflow-hidden rounded-xl border border-border bg-surface shadow-lg">
              <div className="flex items-center gap-3 border-b border-border bg-surface-muted px-4 py-3" aria-hidden="true">
                <div className="flex gap-1.5">
                  <span className="h-2.5 w-2.5 rounded-full bg-danger/70" />
                  <span className="h-2.5 w-2.5 rounded-full bg-warning/70" />
                  <span className="h-2.5 w-2.5 rounded-full bg-success/70" />
                </div>
                <span className="mx-auto inline-flex w-full max-w-xs items-center justify-center gap-1.5 rounded-md border border-border bg-surface px-3 py-1 text-caption text-muted-foreground">
                  <Lock className="h-3 w-3" />
                  app.shiphub.com
                </span>
                <span className="w-[42px]" />
              </div>
              <motion.div
                id={`${baseId}-panel`}
                role="tabpanel"
                aria-labelledby={`${baseId}-tab-${tabs.indexOf(tab)}`}
                animate={{ height }}
                transition={{ duration: reduce ? 0 : 0.28, ease: [0.2, 0.8, 0.2, 1] }}
                className="overflow-hidden"
              >
                <div ref={contentRef} className="p-4 sm:p-6" aria-hidden="true">
                  <AnimatePresence mode="wait" initial={false}>
                    <motion.div key={tab} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.1 }}>
                      {tab === 'Rates' ? <RatesScreen /> : null}
                      {tab === 'Shipments' ? <ShipmentsScreen /> : null}
                      {tab === 'Tracking' ? <TrackingScreen /> : null}
                    </motion.div>
                  </AnimatePresence>
                </div>
                <p className="sr-only">
                  {tab === 'Rates' && 'Example rate comparison listing three courier services with prices and delivery times.'}
                  {tab === 'Shipments' && 'Example shipments table with five shipments and their statuses.'}
                  {tab === 'Tracking' && 'Example tracking timeline for a parcel that is in transit.'}
                </p>
              </motion.div>
            </div>
          </Reveal>
        </div>
        <div className="mx-auto mt-10 grid max-w-4xl gap-6 md:grid-cols-3">
          {bullets.map((item, index) => (
            <Reveal key={item.title} index={index} className="flex gap-3">
              <span className="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-success-soft">
                <Check className="h-3.5 w-3.5 text-success" strokeWidth={3} aria-hidden="true" />
              </span>
              <div>
                <p className="text-body font-semibold">{item.title}</p>
                <p className="mt-0.5 text-small text-muted-foreground">{item.text}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </Container>
    </Section>
  );
}
