/*
 * M8 물류 확장 탭 — F041 장비 신청 · F042 렌탈 주문 · F043 선입고 트래킹.
 * DockReservationPage(/logistics) 탭 확장으로 진입. 기존 도크 예약 컨벤션(카드·필터·토스트) 재사용.
 * 실 API: logisticsExtApi(GET /logistics/ext · POST 신청/주문/등록 · POST 상태전이). 금액은 서버 권위 표시만.
 */
import { useEffect, useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconList, IconTag, IconTruck } from '../../components/ui/icons';
import { ApiRequestError } from '../../api/client';
import {
  logisticsExtApi,
  type EquipmentItem,
  type EquipmentRequestView,
  type InboundView,
  type RentalItem,
  type RentalOrderView,
} from './logisticsExtApi';

function useBoard(eventId: string | null) {
  return useQuery({
    queryKey: ['logi-ext', eventId],
    queryFn: () => logisticsExtApi.board(eventId as string),
    enabled: !!eventId,
    retry: false,
  });
}

function krw(n: number): string {
  return `${(n ?? 0).toLocaleString('ko-KR')}원`;
}

function useToast(): [string | null, (m: string | null) => void] {
  const [toast, setToast] = useState<string | null>(null);
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2600);
    return () => clearTimeout(t);
  }, [toast]);
  return [toast, setToast];
}

/** 상태 배지 — 상태코드별 톤 매핑. */
function StatusPill({ ns, status }: { ns: 'equipment' | 'rental' | 'inbound'; status: string }) {
  const { t } = useTranslation();
  const tone =
    status === 'approved' || status === 'confirmed' || status === 'done' || status === 'delivered' || status === 'delivered_booth'
      ? 'ok'
      : status === 'rejected' || status === 'cancelled'
        ? 'no'
        : 'wait';
  return <span className={`kx-logi__pill kx-logi__pill--${tone}`}>{t(`logistics.${ns}.st.${status}`)}</span>;
}

/* ════════════════════════ 장비 신청 (F041) ════════════════════════ */
export function EquipmentTab({ eventId }: { eventId: string | null }) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const boardQ = useBoard(eventId);
  const [toast, setToast] = useToast();
  const [equipmentId, setEquipmentId] = useState('');
  const [boothNo, setBoothNo] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [useDate, setUseDate] = useState('');
  const [days, setDays] = useState(1);

  const board = boardQ.data;
  const catalog: EquipmentItem[] = board?.equipmentCatalog ?? [];
  const rows: EquipmentRequestView[] = board?.equipmentRequests ?? [];
  const canManage = board?.canManage ?? false;
  const selected = catalog.find((c) => c.id === equipmentId) ?? catalog[0];
  const estimate = selected ? selected.unitPrice * Math.max(1, quantity) * Math.max(1, days) : 0;

  const invalidate = () => qc.invalidateQueries({ queryKey: ['logi-ext', eventId] });

  const submit = useMutation({
    mutationFn: () =>
      logisticsExtApi.requestEquipment(eventId as string, {
        equipmentId: selected?.id ?? '',
        boothNo: boothNo || undefined,
        quantity: Math.max(1, quantity),
        useDate: useDate || undefined,
        days: Math.max(1, days),
      }),
    onSuccess: () => {
      invalidate();
      setToast(t('logistics.submitOk'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  const decide = useMutation({
    mutationFn: (v: { id: string; status: string; reason?: string }) =>
      logisticsExtApi.decideEquipment(eventId as string, v.id, { status: v.status, reason: v.reason }),
    onSuccess: () => {
      invalidate();
      setToast(t('logistics.statusUpdated'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  if (boardQ.isPending) return <Skeleton height={280} />;
  if (boardQ.isError) return <ErrorState message={t('logistics.loadErr')} onRetry={() => boardQ.refetch()} />;

  return (
    <div className="kx-logi__split">
      <section className="kx-card">
        <span className="kx-dock__panel-title"><IconTruck className="kx-title-ic" size={18} />{t('logistics.equipment.formTitle')}</span>
        <div className="kx-dock__form">
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.equipment.item')}</span>
            <select className="kx-dock__select" value={selected?.id ?? ''} onChange={(e) => setEquipmentId(e.target.value)}>
              {catalog.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name} · {krw(c.unitPrice)}/{c.unit}
                </option>
              ))}
            </select>
          </label>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.boothNo')}</span>
            <input className="kx-dock__input" value={boothNo} onChange={(e) => setBoothNo(e.target.value)} placeholder="A-101" />
          </label>
          <div className="kx-logi__row2">
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.qty')}</span>
              <input type="number" min={1} className="kx-dock__input" value={quantity} onChange={(e) => setQuantity(Number(e.target.value) || 1)} />
            </label>
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.equipment.days')}</span>
              <input type="number" min={1} className="kx-dock__input" value={days} onChange={(e) => setDays(Number(e.target.value) || 1)} />
            </label>
          </div>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.equipment.useDate')}</span>
            <input type="date" className="kx-dock__input" value={useDate} onChange={(e) => setUseDate(e.target.value)} />
          </label>
          <p className="kx-logi__estimate">
            {t('logistics.estimate')} <strong>{krw(estimate)}</strong>
          </p>
          <button type="button" className="kx-dock__qr" disabled={submit.isPending || !selected} onClick={() => submit.mutate()}>
            <span className="kx-dock__qr-main">
              <span className="kx-dock__qr-title">{submit.isPending ? t('logistics.submitting') : t('logistics.equipment.submit')}</span>
              <span className="kx-dock__qr-sub">{t('logistics.serverAmountNote')}</span>
            </span>
          </button>
        </div>
      </section>

      <section className="kx-card kx-logi__list">
        <span className="kx-dock__panel-title"><IconList className="kx-title-ic" size={18} />{t('logistics.equipment.listTitle')}</span>
        {rows.length === 0 ? (
          <EmptyState title={t('logistics.equipment.empty')} description={t('logistics.equipment.emptyDesc')} />
        ) : (
          <ul className="kx-logi__items">
            {rows.map((r) => (
              <li key={r.id} className="kx-logi__item">
                <div className="kx-logi__item-main">
                  <span className="kx-logi__item-name">{r.equipmentName}</span>
                  <StatusPill ns="equipment" status={r.status} />
                </div>
                <div className="kx-logi__item-meta">
                  {r.boothNo ? `${r.boothNo} · ` : ''}
                  {t('logistics.qty')} {r.quantity} · {r.days}{t('logistics.equipment.daysUnit')} · <strong>{krw(r.amount)}</strong>
                  {r.useDate ? ` · ${r.useDate}` : ''}
                </div>
                {r.rejectReason ? <div className="kx-logi__reason">{r.rejectReason}</div> : null}
                {canManage && r.status === 'requested' && (
                  <div className="kx-logi__actions">
                    <button className="kx-logi__act kx-logi__act--ok" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'approved' })}>
                      {t('logistics.equipment.approve')}
                    </button>
                    <button className="kx-logi__act kx-logi__act--no" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'rejected', reason: t('logistics.equipment.rejectReason') })}>
                      {t('logistics.equipment.reject')}
                    </button>
                  </div>
                )}
                {canManage && r.status === 'approved' && (
                  <div className="kx-logi__actions">
                    <button className="kx-logi__act" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'done' })}>
                      {t('logistics.equipment.done')}
                    </button>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>
      {toast && <div className="kx-dock__toast" role="status">{toast}</div>}
    </div>
  );
}

/* ════════════════════════ 렌탈 주문 (F042) ════════════════════════ */
export function RentalTab({ eventId }: { eventId: string | null }) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const boardQ = useBoard(eventId);
  const [toast, setToast] = useToast();
  const [itemId, setItemId] = useState('');
  const [boothNo, setBoothNo] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  const board = boardQ.data;
  const catalog: RentalItem[] = board?.rentalCatalog ?? [];
  const rows: RentalOrderView[] = board?.rentalOrders ?? [];
  const canManage = board?.canManage ?? false;
  const selected = catalog.find((c) => c.id === itemId) ?? catalog[0];

  const days = useMemo(() => {
    if (startDate && endDate) {
      const s = new Date(startDate).getTime();
      const e = new Date(endDate).getTime();
      if (!Number.isNaN(s) && !Number.isNaN(e) && e >= s) {
        return Math.floor((e - s) / 86400000) + 1;
      }
    }
    return 1;
  }, [startDate, endDate]);
  const estimate = selected ? selected.dailyPrice * Math.max(1, quantity) * days : 0;

  const invalidate = () => qc.invalidateQueries({ queryKey: ['logi-ext', eventId] });

  const submit = useMutation({
    mutationFn: () =>
      logisticsExtApi.orderRental(eventId as string, {
        itemId: selected?.id ?? '',
        boothNo: boothNo || undefined,
        quantity: Math.max(1, quantity),
        startDate: startDate || undefined,
        endDate: endDate || undefined,
        days,
      }),
    onSuccess: () => {
      invalidate();
      setToast(t('logistics.submitOk'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  const decide = useMutation({
    mutationFn: (v: { id: string; status: string }) => logisticsExtApi.decideRental(eventId as string, v.id, { status: v.status }),
    onSuccess: () => {
      invalidate();
      setToast(t('logistics.statusUpdated'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  if (boardQ.isPending) return <Skeleton height={280} />;
  if (boardQ.isError) return <ErrorState message={t('logistics.loadErr')} onRetry={() => boardQ.refetch()} />;

  return (
    <div className="kx-logi__split">
      <section className="kx-card">
        <span className="kx-dock__panel-title"><IconTag className="kx-title-ic" size={18} />{t('logistics.rental.formTitle')}</span>
        <div className="kx-dock__form">
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.rental.item')}</span>
            <select className="kx-dock__select" value={selected?.id ?? ''} onChange={(e) => setItemId(e.target.value)}>
              {catalog.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name} · {krw(c.dailyPrice)}/{c.unit}
                </option>
              ))}
            </select>
          </label>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.boothNo')}</span>
            <input className="kx-dock__input" value={boothNo} onChange={(e) => setBoothNo(e.target.value)} placeholder="A-101" />
          </label>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.qty')}</span>
            <input type="number" min={1} className="kx-dock__input" value={quantity} onChange={(e) => setQuantity(Number(e.target.value) || 1)} />
          </label>
          <div className="kx-logi__row2">
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.rental.start')}</span>
              <input type="date" className="kx-dock__input" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
            </label>
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.rental.end')}</span>
              <input type="date" className="kx-dock__input" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
            </label>
          </div>
          <p className="kx-logi__estimate">
            {t('logistics.rental.period', { days })} · {t('logistics.estimate')} <strong>{krw(estimate)}</strong>
          </p>
          <button type="button" className="kx-dock__qr" disabled={submit.isPending || !selected} onClick={() => submit.mutate()}>
            <span className="kx-dock__qr-main">
              <span className="kx-dock__qr-title">{submit.isPending ? t('logistics.submitting') : t('logistics.rental.submit')}</span>
              <span className="kx-dock__qr-sub">{t('logistics.serverAmountNote')}</span>
            </span>
          </button>
        </div>
      </section>

      <section className="kx-card kx-logi__list">
        <span className="kx-dock__panel-title"><IconList className="kx-title-ic" size={18} />{t('logistics.rental.listTitle')}</span>
        {rows.length === 0 ? (
          <EmptyState title={t('logistics.rental.empty')} description={t('logistics.rental.emptyDesc')} />
        ) : (
          <ul className="kx-logi__items">
            {rows.map((r) => (
              <li key={r.id} className="kx-logi__item">
                <div className="kx-logi__item-main">
                  <span className="kx-logi__item-name">{r.itemName}</span>
                  <StatusPill ns="rental" status={r.status} />
                </div>
                <div className="kx-logi__item-meta">
                  {r.boothNo ? `${r.boothNo} · ` : ''}
                  {t('logistics.qty')} {r.quantity} · {t('logistics.rental.period', { days: r.days })} · <strong>{krw(r.amount)}</strong>
                  {r.startDate ? ` · ${r.startDate}~${r.endDate ?? ''}` : ''}
                </div>
                {canManage && r.status === 'ordered' && (
                  <div className="kx-logi__actions">
                    <button className="kx-logi__act kx-logi__act--ok" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'confirmed' })}>
                      {t('logistics.rental.confirm')}
                    </button>
                    <button className="kx-logi__act kx-logi__act--no" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'cancelled' })}>
                      {t('logistics.rental.cancel')}
                    </button>
                  </div>
                )}
                {canManage && r.status === 'confirmed' && (
                  <div className="kx-logi__actions">
                    <button className="kx-logi__act" disabled={decide.isPending} onClick={() => decide.mutate({ id: r.id, status: 'delivered' })}>
                      {t('logistics.rental.deliver')}
                    </button>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>
      {toast && <div className="kx-dock__toast" role="status">{toast}</div>}
    </div>
  );
}

/* ════════════════════════ 선입고 트래킹 (F043) ════════════════════════ */
const INBOUND_FLOW = ['registered', 'inbound_scheduled', 'arrived_warehouse', 'delivered_booth'] as const;
const NEXT_INBOUND: Record<string, string | null> = {
  registered: 'inbound_scheduled',
  inbound_scheduled: 'arrived_warehouse',
  arrived_warehouse: 'delivered_booth',
  delivered_booth: null,
};

export function InboundTab({ eventId }: { eventId: string | null }) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const boardQ = useBoard(eventId);
  const [toast, setToast] = useToast();
  const [trackingNo, setTrackingNo] = useState('');
  const [carrier, setCarrier] = useState('');
  const [boothNo, setBoothNo] = useState('');
  const [itemDesc, setItemDesc] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [etaDate, setEtaDate] = useState('');

  const board = boardQ.data;
  const rows: InboundView[] = board?.inbound ?? [];
  const canManage = board?.canManage ?? false;

  const invalidate = () => qc.invalidateQueries({ queryKey: ['logi-ext', eventId] });

  const submit = useMutation({
    mutationFn: () =>
      logisticsExtApi.registerInbound(eventId as string, {
        trackingNo: trackingNo.trim(),
        carrier: carrier || undefined,
        boothNo: boothNo || undefined,
        itemDesc: itemDesc || undefined,
        quantity: Math.max(1, quantity),
        etaDate: etaDate || undefined,
      }),
    onSuccess: () => {
      invalidate();
      setTrackingNo('');
      setToast(t('logistics.submitOk'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  const advance = useMutation({
    mutationFn: (v: { id: string; status: string }) => logisticsExtApi.advanceInbound(eventId as string, v.id, { status: v.status }),
    onSuccess: () => {
      invalidate();
      setToast(t('logistics.statusUpdated'));
    },
    onError: (e) => setToast(e instanceof ApiRequestError ? e.message : t('logistics.submitErr')),
  });

  if (boardQ.isPending) return <Skeleton height={280} />;
  if (boardQ.isError) return <ErrorState message={t('logistics.loadErr')} onRetry={() => boardQ.refetch()} />;

  return (
    <div className="kx-logi__split">
      <section className="kx-card">
        <span className="kx-dock__panel-title"><IconTruck className="kx-title-ic" size={18} />{t('logistics.inbound.formTitle')}</span>
        <div className="kx-dock__form">
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.inbound.trackingNo')}</span>
            <input className="kx-dock__input" value={trackingNo} onChange={(e) => setTrackingNo(e.target.value)} placeholder="1234-5678-9012" />
          </label>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.inbound.carrier')}</span>
            <input className="kx-dock__input" value={carrier} onChange={(e) => setCarrier(e.target.value)} />
          </label>
          <div className="kx-logi__row2">
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.boothNo')}</span>
              <input className="kx-dock__input" value={boothNo} onChange={(e) => setBoothNo(e.target.value)} placeholder="A-101" />
            </label>
            <label className="kx-dock__field">
              <span className="kx-dock__label">{t('logistics.qty')}</span>
              <input type="number" min={1} className="kx-dock__input" value={quantity} onChange={(e) => setQuantity(Number(e.target.value) || 1)} />
            </label>
          </div>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.inbound.itemDesc')}</span>
            <input className="kx-dock__input" value={itemDesc} onChange={(e) => setItemDesc(e.target.value)} />
          </label>
          <label className="kx-dock__field">
            <span className="kx-dock__label">{t('logistics.inbound.eta')}</span>
            <input type="date" className="kx-dock__input" value={etaDate} onChange={(e) => setEtaDate(e.target.value)} />
          </label>
          <button type="button" className="kx-dock__qr" disabled={submit.isPending || !trackingNo.trim()} onClick={() => submit.mutate()}>
            <span className="kx-dock__qr-main">
              <span className="kx-dock__qr-title">{submit.isPending ? t('logistics.submitting') : t('logistics.inbound.submit')}</span>
              <span className="kx-dock__qr-sub">{t('logistics.inbound.submitSub')}</span>
            </span>
          </button>
        </div>
      </section>

      <section className="kx-card kx-logi__list">
        <span className="kx-dock__panel-title"><IconList className="kx-title-ic" size={18} />{t('logistics.inbound.listTitle')}</span>
        {rows.length === 0 ? (
          <EmptyState title={t('logistics.inbound.empty')} description={t('logistics.inbound.emptyDesc')} />
        ) : (
          <ul className="kx-logi__items">
            {rows.map((r) => {
              const step = INBOUND_FLOW.indexOf(r.status as (typeof INBOUND_FLOW)[number]);
              const next = NEXT_INBOUND[r.status];
              return (
                <li key={r.id} className="kx-logi__item">
                  <div className="kx-logi__item-main">
                    <span className="kx-logi__item-name">{r.trackingNo}</span>
                    <StatusPill ns="inbound" status={r.status} />
                  </div>
                  <div className="kx-logi__item-meta">
                    {r.carrier ? `${r.carrier} · ` : ''}
                    {r.boothNo ? `${r.boothNo} · ` : ''}
                    {r.itemDesc ?? ''} {t('logistics.qty')} {r.quantity}
                    {r.etaDate ? ` · ${t('logistics.inbound.eta')} ${r.etaDate}` : ''}
                  </div>
                  <div className="kx-logi__track" aria-hidden="true">
                    {INBOUND_FLOW.map((s, i) => (
                      <span key={s} className={`kx-logi__track-dot ${i <= step ? 'is-done' : ''}`} />
                    ))}
                  </div>
                  {canManage && next && (
                    <div className="kx-logi__actions">
                      <button className="kx-logi__act kx-logi__act--ok" disabled={advance.isPending} onClick={() => advance.mutate({ id: r.id, status: next })}>
                        {t(`logistics.inbound.advance.${next}`)}
                      </button>
                    </div>
                  )}
                </li>
              );
            })}
          </ul>
        )}
      </section>
      {toast && <div className="kx-dock__toast" role="status">{toast}</div>}
    </div>
  );
}
