'use client';

import { animate, useReducedMotion } from 'framer-motion';
import { Info } from 'lucide-react';
import { useEffect, useId, useRef, useState } from 'react';

import { Card } from '@/components/ui/card';
import { Select } from '@/components/ui/input';

type Service = 'Economy' | 'Standard' | 'Express';

// Made-up illustration formula. Not a real quote and not connected to any rate API.
const baseByService: Record<Service, number> = { Economy: 9.5, Standard: 14, Express: 24 };
const perKgByService: Record<Service, number> = { Economy: 1.9, Standard: 2.6, Express: 4.1 };

function AnimatedNumber({ value }: { value: number }) {
  const reduce = useReducedMotion();
  const [display, setDisplay] = useState(value);
  const previous = useRef(value);

  useEffect(() => {
    const from = previous.current;
    previous.current = value;
    const controls = animate(from, value, {
      duration: reduce ? 0 : 0.35,
      ease: [0.2, 0.8, 0.2, 1],
      onUpdate: (latest) => setDisplay(latest),
    });
    return () => controls.stop();
  }, [reduce, value]);

  return <span className="tabular-nums">{display.toFixed(2)}</span>;
}

export function PricingPlayground() {
  const weightId = useId();
  const serviceId = useId();
  const [weight, setWeight] = useState(2.5);
  const [service, setService] = useState<Service>('Standard');

  const courier = Math.round((baseByService[service] + weight * perKgByService[service]) * 100) / 100;
  const fill = ((weight - 0.5) / (20 - 0.5)) * 100;

  return (
    <Card variant="gradient" className="rounded-2xl p-6 md:p-8">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h2 className="font-display text-h2 font-bold">Try an example</h2>
          <p className="mt-1 text-small text-muted-foreground">Move the slider to see how the total is built.</p>
        </div>
        <span className="inline-flex items-center gap-1.5 rounded-pill bg-warning-soft px-2.5 py-1 text-caption font-semibold text-warning">
          <Info className="h-3.5 w-3.5" aria-hidden="true" />
          Example values only
        </span>
      </div>

      <div className="mt-8">
        <div className="flex items-center justify-between">
          <label htmlFor={weightId} className="text-small font-semibold">
            Parcel weight
          </label>
          <span className="rounded-md bg-surface-muted px-2 py-0.5 text-small font-semibold tabular-nums">{weight.toFixed(1)} kg</span>
        </div>
        <input
          id={weightId}
          type="range"
          min={0.5}
          max={20}
          step={0.5}
          value={weight}
          onChange={(event) => setWeight(Number(event.target.value))}
          aria-valuetext={`${weight.toFixed(1)} kilograms`}
          className="mt-4 h-2 w-full cursor-pointer appearance-none rounded-pill bg-transparent [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-2 [&::-moz-range-thumb]:border-primary [&::-moz-range-thumb]:bg-surface [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-primary [&::-webkit-slider-thumb]:bg-surface [&::-webkit-slider-thumb]:shadow-md"
          style={{ background: `linear-gradient(90deg, rgb(var(--primary)) ${fill}%, rgb(var(--border)) ${fill}%)` }}
        />
        <div className="mt-2 flex justify-between text-caption text-subtle-foreground">
          <span>0.5 kg</span>
          <span>20 kg</span>
        </div>
      </div>

      <div className="mt-6 grid gap-1.5">
        <label htmlFor={serviceId} className="text-small font-semibold">
          Service
        </label>
        <Select id={serviceId} value={service} onChange={(event) => setService(event.target.value as Service)}>
          <option value="Economy">Economy</option>
          <option value="Standard">Standard</option>
          <option value="Express">Express</option>
        </Select>
      </div>

      <dl className="mt-8 grid gap-3 rounded-xl border border-border bg-surface-muted p-5 text-body">
        <div className="flex justify-between">
          <dt className="text-muted-foreground">Courier rate</dt>
          <dd className="font-semibold">
            <AnimatedNumber value={courier} />
          </dd>
        </div>
        <div className="flex justify-between">
          <dt className="text-muted-foreground">Platform fee</dt>
          <dd className="font-medium text-success">included</dd>
        </div>
        <div className="my-1 border-t border-dashed border-border-strong" aria-hidden="true" />
        <div className="flex items-end justify-between">
          <dt className="font-semibold">Total</dt>
          <dd className="font-display text-[2.25rem] font-extrabold leading-none tracking-[-0.03em]">
            <AnimatedNumber value={courier} />
          </dd>
        </div>
      </dl>
      <p className="sr-only" aria-live="polite">
        Example total {courier.toFixed(2)} for {weight.toFixed(1)} kilograms, {service}.
      </p>
      <p className="mt-3 text-caption text-muted-foreground">Example values only. An illustration with a made-up formula, not a live quote.</p>
    </Card>
  );
}
