// @design-system: vendor/ShipModal
// Vendor: modal to enter carrier + tracking number and confirm shipment.

'use client';

import { useState, type SubmitEvent } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/overlays/Dialog';
import { Button } from '@/components/ui/primitives/Button';
import { Input } from '@/components/ui/primitives/Input';
import { Label } from '@/components/ui/primitives/Label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/primitives/Select';
import { useT } from '@/lib/i18n/react';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
// Manual-carrier subset: excludes pickup (no carrier) and wolt_drive (auto-dispatched).
import { type MANUAL_CARRIER } from '@/lib/enums/carrier';

// ─── Types ────────────────────────────────────────────────────────────────────

type Props = {
  shipment: { id: string };
  onClose(): void;
  onShipped(): void;
};

type CarrierKey = (typeof MANUAL_CARRIER)[number];

// ─── Component ────────────────────────────────────────────────────────────────

export function ShipModal({ shipment, onClose, onShipped }: Props) {
  const t = useT('vendor_shipping');
  const [carrier, setCarrier] = useState<CarrierKey>('israel_post');
  const [trackingNumber, setTrackingNumber] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Build carrier options after t() is available (avoids dynamic key lookup)
  const carrierOptions: Array<{ value: CarrierKey; label: string }> = [
    { value: 'israel_post', label: t('carrier_israel_post') },
    { value: 'yedioth_couriers', label: t('carrier_yedioth_couriers') },
    { value: 'cheetah', label: t('carrier_cheetah') },
    { value: 'hfd', label: t('carrier_hfd') },
    { value: 'baldar', label: t('carrier_baldar') },
    { value: 'other', label: t('carrier_other') },
  ];

  async function submit(e: SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!trackingNumber.trim()) {
      setError(t('tracking_required'));
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const csrf = getCsrfToken();
      const res = await fetch(`/api/vendor/shipments/${shipment.id}/ship`, {
        method: 'PUT',
        headers: {
          'content-type': 'application/json',
          'x-csrf-token': csrf,
        },
        body: JSON.stringify({ carrier, trackingNumber }),
      });
      if (!res.ok) {
        setError(t('ship_failed'));
        return;
      }
      onShipped();
    } catch (err) {
      captureCaught(err, { scope: 'ShipModal.submit' });
      setError(t('ship_failed'));
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog
      open
      onOpenChange={(open) => {
        if (!open) onClose();
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('ship_modal_title')}</DialogTitle>
        </DialogHeader>
        <form onSubmit={submit} className="flex flex-col gap-4">
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="ship-carrier-select">{t('carrier_label')}</Label>
            <Select value={carrier} onValueChange={(v) => setCarrier(v as CarrierKey)}>
              <SelectTrigger id="ship-carrier-select" aria-label={t('carrier_label')}>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {carrierOptions.map(({ value, label }) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="ship-tracking-input">{t('tracking_label')}</Label>
            <Input
              id="ship-tracking-input"
              value={trackingNumber}
              onChange={(e) => setTrackingNumber(e.target.value)}
              placeholder={t('tracking_placeholder')}
              aria-label={t('tracking_label')}
              autoComplete="off"
            />
          </div>
          {error && (
            <p role="alert" className="text-destructive text-sm">
              {error}
            </p>
          )}
          <DialogFooter>
            <Button type="button" variant="secondary" onClick={onClose} disabled={loading}>
              {t('cancel')}
            </Button>
            <Button type="submit" disabled={loading} loading={loading}>
              {t('ship_confirm')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
