'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { Hash, PackageCheck, ShieldCheck, Truck } from 'lucide-react';

import { describedBy, FormField } from '@/components/forms/form-field';
import { Radio } from '@/components/ui/choice';
import { Input, Textarea } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { declaredTotalMinor, type ShipmentDraft } from '@/lib/wizard';

const major = (minor: number): string => `${Math.floor(minor / 100)}.${String(minor % 100).padStart(2, '0')}`;

export function OptionsStep({
  draft,
  errors,
  international,
  currency,
  onEdit,
}: {
  draft: ShipmentDraft;
  errors: Record<string, string>;
  international: boolean;
  currency: string;
  onEdit: (draft: ShipmentDraft, clearQuote: boolean) => void;
}) {
  const reduce = useReducedMotion();
  return (
    <div className="grid gap-6">
      {international ? (
        <section className="rounded-xl border border-border bg-surface p-5 shadow-xs md:p-6">
          <fieldset>
            <legend className="font-display text-h3 font-bold">Duties and taxes</legend>
            <p className="mt-0.5 text-small text-muted-foreground">Choose who pays import duties and taxes at the destination.</p>
            <div className="mt-4 grid gap-3 sm:grid-cols-2">
              <Radio
                name="duties"
                label="Sender pays"
                hint="Duties are billed with the shipment. The parcel arrives with nothing to pay."
                icon={<Truck />}
                checked={draft.taxesDutiesPaidBy === 'Sender'}
                onChange={() => onEdit({ ...draft, taxesDutiesPaidBy: 'Sender' }, true)}
              />
              <Radio
                name="duties"
                label="Recipient pays"
                hint="The recipient pays any duties and taxes on delivery."
                icon={<PackageCheck />}
                checked={draft.taxesDutiesPaidBy === 'Recipient'}
                onChange={() => onEdit({ ...draft, taxesDutiesPaidBy: 'Recipient' }, true)}
              />
            </div>
          </fieldset>
        </section>
      ) : null}

      <section className="rounded-xl border border-border bg-surface p-5 shadow-xs md:p-6" aria-labelledby="insurance-title">
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-start gap-3">
            <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-success-soft text-success">
              <ShieldCheck className="h-[18px] w-[18px]" aria-hidden="true" />
            </span>
            <div>
              <h3 id="insurance-title" className="font-display text-h3 font-bold">
                Insurance
              </h3>
              <p className="mt-0.5 text-small text-muted-foreground">Cover loss or damage up to the insured amount.</p>
            </div>
          </div>
          <Switch
            labelledBy="insurance-title"
            checked={draft.isInsured}
            onCheckedChange={(isInsured) => onEdit({ ...draft, isInsured, insuredAmount: isInsured ? major(declaredTotalMinor(draft)) : '' }, true)}
          />
        </div>
        <AnimatePresence initial={false}>
          {draft.isInsured ? (
            <motion.div
              key="insured"
              initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
              animate={reduce ? { opacity: 1 } : { opacity: 1, height: 'auto' }}
              exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
              transition={{ duration: 0.22, ease: [0.2, 0.8, 0.2, 1] }}
              className="overflow-hidden"
            >
              <div className="mt-4 grid gap-1.5 border-t border-border pt-4 sm:max-w-xs">
                <FormField id="insured-amount" label="Insured amount" error={errors.insuredAmount}>
                  <Input
                    id="insured-amount"
                    inputMode="decimal"
                    className="tabular-nums"
                    value={draft.insuredAmount}
                    trailing={<span className="mr-3 text-small text-subtle-foreground">{currency}</span>}
                    aria-invalid={errors.insuredAmount !== undefined ? true : undefined}
                    aria-describedby={describedBy('insured-amount', undefined, errors.insuredAmount)}
                    onChange={(event) => onEdit({ ...draft, insuredAmount: event.target.value }, true)}
                  />
                </FormField>
                <p className="text-caption text-muted-foreground">Rates on the next step are quoted for this insured amount.</p>
              </div>
            </motion.div>
          ) : null}
        </AnimatePresence>
      </section>

      <section className="grid gap-4 rounded-xl border border-border bg-surface p-5 shadow-xs md:p-6" aria-labelledby="reference-title">
        <div className="flex items-center gap-3">
          <span className="grid h-9 w-9 place-items-center rounded-lg bg-primary-soft text-primary">
            <Hash className="h-[18px] w-[18px]" aria-hidden="true" />
          </span>
          <h3 id="reference-title" className="font-display text-h3 font-bold">
            Reference and notes
          </h3>
        </div>
        <FormField
          id="reference"
          label="Reference (optional)"
          hint="An order number or internal ID. Printed on the label."
          error={errors.reference}
          labelAction={
            <span className={cn('text-caption tabular-nums', draft.reference.length >= 50 ? 'text-warning' : 'text-subtle-foreground')} aria-live="polite">
              {draft.reference.length}/50
            </span>
          }
        >
          <Input
            id="reference"
            maxLength={50}
            value={draft.reference}
            aria-invalid={errors.reference !== undefined ? true : undefined}
            aria-describedby={describedBy('reference', 'hint', errors.reference)}
            onChange={(event) => onEdit({ ...draft, reference: event.target.value }, false)}
          />
        </FormField>
        <FormField id="notes" label="Notes (optional)" hint="Internal notes for your team. They are not sent to the courier.">
          <Textarea id="notes" value={draft.notes} aria-describedby="notes-hint" onChange={(event) => onEdit({ ...draft, notes: event.target.value }, false)} />
        </FormField>
      </section>
    </div>
  );
}
