'use client';

import { Plus, Scale, Trash2 } from 'lucide-react';
import { useState } from 'react';

import { describedBy, FieldError, FormField } from '@/components/forms/form-field';
import { Input } from '@/components/ui/input';
import { Segmented } from '@/components/ui/segmented';
import { cn } from '@/lib/utils';
import { BOX_PRESETS, toMetric, volumetricKg, type ParcelDraft, type ShipmentDraft } from '@/lib/wizard';

type Preset = { weightKg: number; lengthCm: number; widthCm: number; heightCm: number };

/** Mini isometric box whose size follows the preset's volume. */
function BoxIcon({ preset }: { preset: Preset }) {
  const volume = preset.lengthCm * preset.widthCm * preset.heightCm;
  const scale = Math.min(1, Math.max(0.55, Math.cbrt(volume) / 40));
  return (
    <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" aria-hidden="true">
      <g transform={`translate(12 13) scale(${scale}) translate(-12 -13)`}>
        <path d="M12 4l8 4v9l-8 4-8-4V8l8-4z" className="fill-primary-soft stroke-primary" strokeWidth="1.5" strokeLinejoin="round" />
        <path d="M4 8l8 4 8-4M12 12v9" className="stroke-primary" strokeWidth="1.5" strokeLinejoin="round" />
      </g>
    </svg>
  );
}

const fields = ['weight', 'length', 'width', 'height'] as const;
const fieldLabel: Record<(typeof fields)[number], string> = { weight: 'Weight', length: 'Length', width: 'Width', height: 'Height' };

export function ParcelFields({
  draft,
  errors,
  onChange,
  onUnit,
  onPreset,
  defaultParcel,
}: {
  draft: ShipmentDraft;
  errors: Record<string, string>;
  onChange: (parcels: ParcelDraft[]) => void;
  onUnit: (unit: ShipmentDraft['unit']) => void;
  onPreset: (preset: Preset) => void;
  defaultParcel?: Preset | null;
}) {
  const [flash, setFlash] = useState(0);
  const weightUnit = draft.unit === 'metric' ? 'kg' : 'lb';
  const sizeUnit = draft.unit === 'metric' ? 'cm' : 'in';
  const presets: Array<{ id: string; label: string; preset: Preset }> = [
    ...BOX_PRESETS.map((preset) => ({ id: preset.id, label: preset.label, preset })),
    ...(defaultParcel === undefined || defaultParcel === null ? [] : [{ id: 'default', label: 'My default', preset: defaultParcel }]),
  ];

  return (
    <div className="grid gap-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-2" role="group" aria-label="Box presets">
          {presets.map(({ id, label, preset }) => (
            <button
              key={id}
              type="button"
              onClick={() => {
                onPreset(preset);
                setFlash((value) => value + 1);
              }}
              className="inline-flex h-9 items-center gap-2 rounded-pill border border-border bg-surface pl-2 pr-3 text-small font-medium text-foreground transition-colors hover:border-primary/40 hover:bg-primary-soft"
            >
              <BoxIcon preset={preset} />
              {label}
            </button>
          ))}
        </div>
        <Segmented<ShipmentDraft['unit']>
          size="sm"
          label="Units"
          value={draft.unit}
          onChange={onUnit}
          options={[
            { value: 'metric', label: 'kg · cm' },
            { value: 'imperial', label: 'lb · in' },
          ]}
        />
      </div>

      {draft.parcels.map((parcel, index) => {
        const metric = {
          weightKg: toMetric(Number(parcel.weight), draft.unit, 'weight'),
          lengthCm: toMetric(Number(parcel.length), draft.unit, 'length'),
          widthCm: toMetric(Number(parcel.width), draft.unit, 'length'),
          heightCm: toMetric(Number(parcel.height), draft.unit, 'length'),
        };
        const ready = [metric.weightKg, metric.lengthCm, metric.widthCm, metric.heightCm].every((value) => Number.isFinite(value) && value > 0);
        return (
          <section key={index} className="rounded-xl border border-border bg-surface p-5 shadow-xs" aria-labelledby={`parcel-${index}-title`}>
            <div className="flex items-center justify-between gap-3">
              <h3 id={`parcel-${index}-title`} className="font-display text-small font-bold">
                Parcel {index + 1}
              </h3>
              {draft.parcels.length > 1 ? (
                <button
                  type="button"
                  aria-label={`Remove parcel ${index + 1}`}
                  onClick={() => onChange(draft.parcels.filter((_, itemIndex) => itemIndex !== index))}
                  className="grid h-8 w-8 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-danger-soft hover:text-danger"
                >
                  <Trash2 className="h-4 w-4" aria-hidden="true" />
                </button>
              ) : null}
            </div>
            <div key={`flash-${flash}`} className={cn('mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4', flash > 0 && index === 0 && 'motion-safe:[&_input]:animate-[preset-flash_700ms_ease-out]')}>
              {fields.map((field) => {
                const id = `parcel-${index}-${field}`;
                const error = errors[`parcels.${index}.${field}`];
                return (
                  <FormField key={field} id={id} label={fieldLabel[field]} error={error}>
                    <Input
                      id={id}
                      inputMode="decimal"
                      value={parcel[field]}
                      aria-invalid={error !== undefined ? true : undefined}
                      aria-describedby={describedBy(id, undefined, error)}
                      className="tabular-nums"
                      trailing={<span className="mr-3 text-small text-subtle-foreground">{field === 'weight' ? weightUnit : sizeUnit}</span>}
                      onChange={(event) => {
                        const next = draft.parcels.map((item, itemIndex) => (itemIndex === index ? { ...item, [field]: event.target.value } : item));
                        onChange(next);
                      }}
                    />
                  </FormField>
                );
              })}
            </div>
            {ready ? (
              <p className="mt-4 flex items-start gap-2 rounded-lg bg-info-soft px-3 py-2 text-caption text-foreground">
                <Scale className="mt-0.5 h-3.5 w-3.5 shrink-0 text-info" aria-hidden="true" />
                <span>
                  Volumetric weight is about <span className="font-semibold tabular-nums">{volumetricKg({ weightKg: metric.weightKg, lengthCm: metric.lengthCm, widthCm: metric.widthCm, heightCm: metric.heightCm })} kg</span>. Couriers bill the higher of the actual and volumetric weight.
                </span>
              </p>
            ) : null}
          </section>
        );
      })}
      {errors.parcels === undefined ? null : <FieldError id="parcels-error">{errors.parcels}</FieldError>}
      <button
        type="button"
        onClick={() => onChange([...draft.parcels, { weight: '', length: '', width: '', height: '' }])}
        disabled={draft.parcels.length >= 10}
        className="flex h-12 items-center justify-center gap-2 rounded-xl border-2 border-dashed border-border text-small font-semibold text-muted-foreground transition-colors hover:border-primary/40 hover:bg-primary-soft hover:text-primary disabled:cursor-not-allowed disabled:opacity-50"
      >
        <Plus className="h-4 w-4" aria-hidden="true" />
        Add another parcel
      </button>
    </div>
  );
}
