import { useState, useEffect, useCallback, useMemo } from 'react';
import Link from 'next/link';
import useSWR, { mutate } from 'swr';
import { useApi } from '@/lib/useApi';
import {
  listCabinetItems,
  getCabinetSummary,
  createCabinetItem,
  adjustCabinetItemQuantity,
  deleteCabinetItem,
} from '@/services/cabinet';
import { listMedicines } from '@/services/medicines';
import {
  DosageUnit,
  CabinetItemStatus,
  allowedUnitsForForm,
  defaultUnitForForm,
} from '@meshitrack/shared';
import type { MedicineForm, CreateCabinetItemInput } from '@meshitrack/shared';
import { Icon } from '@/components/ui/Icon';
import type { IconName } from '@/components/ui/Icon';

type CabinetItem = {
  _id: string;
  medicineId: string;
  medicineName: string;
  medicineStrength: number;
  medicineStrengthUnit: string;
  medicineForm: string;
  medicineProductId?: string;
  medicineProductBrand?: string;
  concentration?: number;
  concentrationUnit?: string;
  quantity: number;
  unit: string;
  expirationDate?: string;
  status: string;
  notes?: string;
};

type SummaryItem = {
  medicineId: string;
  medicineName: string;
  medicineStrength: number;
  medicineStrengthUnit: string;
  medicineForm: string;
  totalQuantity: number;
  unit: string;
  earliestExpiry: string | null;
  itemCount: number;
};

type MedicineOption = {
  _id: string;
  name: string;
  strength: number;
  strengthUnit: string;
  form: string;
};

const FORM_LABELS: Record<string, string> = {
  tablet: 'Tablet',
  capsule: 'Capsule',
  liquid: 'Liquid',
  injection: 'Injection',
  other: 'Other',
};

const UNIT_LABELS: Record<string, string> = {
  tablet: 'tablets',
  capsule: 'capsules',
  ml: 'mL',
  vial: 'vials',
  dose: 'doses',
};

const STATUS_LABELS: Record<string, string> = {
  active: 'Active',
  depleted: 'Depleted',
  expired: 'Expired',
};

const VIZ_COLORS = [
  'var(--viz-1)',
  'var(--viz-2)',
  'var(--viz-3)',
  'var(--viz-4)',
  'var(--viz-5)',
  'var(--viz-6)',
];

function vizColor(index: number): string {
  return VIZ_COLORS[index % VIZ_COLORS.length] ?? VIZ_COLORS[0]!;
}

function iconForForm(form: string): IconName {
  if (form === 'injection') return 'injection';
  if (form === 'capsule') return 'capsule';
  if (form === 'liquid') return 'vial';
  return 'pill';
}

function getLevel(earliestExpiry: string | null): 'ok' | 'expiring' | 'critical' {
  if (!earliestExpiry) return 'ok';
  const days = Math.ceil((new Date(earliestExpiry).getTime() - Date.now()) / 86400000);
  if (days <= 0) return 'critical';
  if (days <= 30) return 'expiring';
  return 'ok';
}

function formatDate(dateStr?: string): string {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleDateString();
}

function daysUntilExpiry(dateStr?: string): string {
  if (!dateStr) return '';
  const days = Math.ceil((new Date(dateStr).getTime() - Date.now()) / 86400000);
  if (days <= 0) return '(expired)';
  if (days === 1) return '(1 day)';
  return `(${days} days)`;
}

function expiryTextColor(dateStr?: string): string {
  if (!dateStr) return 'var(--ink-muted)';
  const days = Math.ceil((new Date(dateStr).getTime() - Date.now()) / 86400000);
  if (days <= 0) return 'var(--danger)';
  if (days <= 30) return 'var(--warn)';
  return 'var(--ok)';
}

// ─── ExpiryBar ───────────────────────────────────────────────────────────────

function ExpiryBar({ expirationDate }: { expirationDate: string | null }) {
  if (!expirationDate) {
    return (
      <div className="daysbar">
        <div className="daysbar__track" />
        <div className="daysbar__label num">
          <span className="daysbar__num" style={{ color: 'var(--ink-faint)' }}>
            —
          </span>
          <span className="daysbar__unit">exp</span>
        </div>
      </div>
    );
  }
  const daysLeft = Math.ceil((new Date(expirationDate).getTime() - Date.now()) / 86400000);
  const pct = Math.max(0, Math.min(100, (daysLeft / 365) * 100));
  const tone = daysLeft <= 0 ? 'critical' : daysLeft <= 30 ? 'low' : 'ok';
  return (
    <div className={`daysbar daysbar--${tone}`}>
      <div className="daysbar__track">
        <div className="daysbar__fill" style={{ width: `${pct}%` }} />
      </div>
      <div className="daysbar__label num">
        <span className="daysbar__num">{Math.max(0, daysLeft)}</span>
        <span className="daysbar__unit">days</span>
      </div>
    </div>
  );
}

// ─── StatsStrip ──────────────────────────────────────────────────────────────

function StatsStrip({ items }: { items: SummaryItem[] }) {
  const now = Date.now();
  const expiringSoon = items.filter((i) => {
    if (!i.earliestExpiry) return false;
    const d = Math.ceil((new Date(i.earliestExpiry).getTime() - now) / 86400000);
    return d > 0 && d <= 30;
  }).length;
  const expired = items.filter((i) => {
    if (!i.earliestExpiry) return false;
    return new Date(i.earliestExpiry).getTime() <= now;
  }).length;
  const totalLots = items.reduce((s, i) => s + i.itemCount, 0);

  const stats = [
    { label: 'Medicines', value: items.length, hint: 'distinct medicines', tone: 'ink' },
    {
      label: 'Expiring <30d',
      value: expiringSoon,
      hint: 'check dates soon',
      tone: expiringSoon > 0 ? 'warn' : 'ink',
    },
    {
      label: 'Expired',
      value: expired,
      hint: 'need to discard',
      tone: expired > 0 ? 'danger' : 'ink',
    },
    { label: 'Total lots', value: totalLots, hint: 'individual packages', tone: 'brand' },
  ];

  return (
    <div className="cab-summary" style={{ marginBottom: 20 }}>
      {stats.map((s) => (
        <div key={s.label} className={`cab-summary__item cab-summary__item--${s.tone}`}>
          <div className="cab-summary__label">{s.label}</div>
          <div className="cab-summary__value num">{s.value}</div>
          <div className="cab-summary__hint">{s.hint}</div>
        </div>
      ))}
    </div>
  );
}

// ─── CabinetTab ──────────────────────────────────────────────────────────────

export function CabinetTab({ householdId }: { householdId: string }) {
  const [view, setView] = useState<'summary' | 'detail'>('summary');
  const [error, setError] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [filterStatus, setFilterStatus] = useState('');
  const [expandedMedicine, setExpandedMedicine] = useState<string | null>(null);
  const [expandedItems, setExpandedItems] = useState<CabinetItem[]>([]);
  const [expandLoading, setExpandLoading] = useState(false);

  const summaryKey = householdId && view === 'summary' ? `cabinet-summary-${householdId}` : null;
  const detailKey = householdId && view === 'detail' ? `cabinet-items-${householdId}-${filterStatus}` : null;

  const { data: summaryResponse, mutate: mutateSummary, isLoading: summaryLoading, error: summaryError } = useSWR(
    summaryKey,
    () => getCabinetSummary(householdId!),
  );

  const { data: detailResponse, mutate: mutateDetail, isLoading: detailLoading, error: detailError } = useSWR(
    detailKey,
    () =>
      listCabinetItems(householdId!, {
        status: (filterStatus as CabinetItemStatus) || undefined,
        limit: 50,
      }),
  );

  useEffect(() => {
    const err = summaryError || detailError;
    if (err) {
      setError(err instanceof Error ? err.message : 'Failed to load cabinet');
    }
  }, [summaryError, detailError]);

  const summaryItems = summaryResponse?.data ?? [];
  const cabinetItems = detailResponse?.data ?? [];
  const loading = (view === 'summary' && summaryLoading) || (view === 'detail' && detailLoading);



  const refreshExpanded = async (medId: string) => {
    if (!householdId) return;
    setExpandLoading(true);
    try {
      const result = await listCabinetItems(householdId, {
        medicineId: medId,
        status: CabinetItemStatus.ACTIVE,
        limit: 50,
      });
      setExpandedItems(result.data);
      if (result.data.length === 0) {
        setExpandedMedicine(null);
      }
    } catch {
      setExpandedItems([]);
    } finally {
      setExpandLoading(false);
    }
  };

  async function handleExpand(medicineId: string) {
    if (!householdId) return;
    if (expandedMedicine === medicineId) {
      setExpandedMedicine(null);
      setExpandedItems([]);
      return;
    }
    setExpandedMedicine(medicineId);
    refreshExpanded(medicineId);
  }

  async function handleAdjust(itemId: string, delta: number) {
    if (!householdId) return;
    
    // Optimistic updates
    if (view === 'summary') {
      mutateSummary(async (current) => {
        if (!current) return current;
        // Finding which medicine this item belongs to is hard without more info in the ID,
        // but summary view items are aggregated.
        // For simplicity in summary view, we'll just trigger a refresh or find by mapping.
        // However, we can also mutate the expanded items if they are visible.
        return current;
      }, { revalidate: false });

      if (expandedMedicine) {
        setExpandedItems(prev => prev.map(item => 
          item._id === itemId ? { ...item, quantity: Math.max(0, item.quantity + delta) } : item
        ));
      }
    } else {
      mutateDetail(async (current) => {
        if (!current) return current;
        return {
          ...current,
          data: current.data.map(item => 
            item._id === itemId ? { ...item, quantity: Math.max(0, item.quantity + delta) } : item
          )
        };
      }, { revalidate: false });
    }

    try {
      await adjustCabinetItemQuantity(householdId, itemId, { delta });
      mutateSummary();
      mutateDetail();
      if (expandedMedicine) refreshExpanded(expandedMedicine);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to adjust quantity');
      mutateSummary();
      mutateDetail();
    }
  }

  async function handleDelete(itemId: string) {
    if (!householdId || !window.confirm('Delete this item permanently?')) return;
    try {
      await deleteCabinetItem(householdId, itemId);
      mutateSummary();
      mutateDetail();
      if (expandedMedicine) refreshExpanded(expandedMedicine);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete');
    }
  }

  return (
    <div>
      {/* Stats strip — only in summary view once loaded */}
      {view === 'summary' && !loading && summaryItems.length > 0 && (
        <StatsStrip items={summaryItems} />
      )}

      {/* Toolbar */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 12,
          marginBottom: 16,
          flexWrap: 'wrap',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div className="mt-seg">
            <button
              onClick={() => setView('summary')}
              className={view === 'summary' ? 'is-active' : ''}
            >
              Summary
            </button>
            <button
              onClick={() => setView('detail')}
              className={view === 'detail' ? 'is-active' : ''}
            >
              All Items
            </button>
          </div>

          {view === 'detail' && (
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="mt-field"
              style={{ width: 'auto', padding: '5px 10px', fontSize: 12 }}
            >
              <option value="">All Statuses</option>
              {Object.values(CabinetItemStatus).map((s) => (
                <option key={s} value={s}>
                  {STATUS_LABELS[s] ?? s}
                </option>
              ))}
            </select>
          )}
        </div>

        <button onClick={() => setShowForm(!showForm)} className="mt-btn mt-btn--primary">
          <Icon name="plus" size={14} />
          {showForm ? 'Cancel' : 'Add to Cabinet'}
        </button>
      </div>

      {/* Error */}
      {error && (
        <div
          style={{
            marginBottom: 16,
            background: 'var(--danger-soft)',
            border: '1px solid color-mix(in oklab, var(--danger) 25%, var(--danger-soft))',
            borderRadius: 'var(--r-sm)',
            padding: '10px 14px',
            fontSize: 13,
            color: 'var(--danger)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 12,
          }}
        >
          <span>{error}</span>
          <button
            onClick={() => setError('')}
            style={{
              fontSize: 12,
              color: 'var(--danger)',
              textDecoration: 'underline',
              cursor: 'pointer',
            }}
          >
            Dismiss
          </button>
        </div>
      )}

      {/* Add form */}
      {showForm && (
        <AddToCabinetForm
          householdId={householdId}
          onCreated={() => {
            setShowForm(false);
            mutateSummary();
            mutateDetail();
          }}
          onCancel={() => setShowForm(false)}
        />
      )}

      {/* Content */}
      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {Array.from({ length: 3 }).map((_, i) => (
            <div
              key={i}
              style={{
                height: 72,
                borderRadius: 'var(--r-md)',
                background: 'var(--bg-inset)',
              }}
            />
          ))}
        </div>
      ) : view === 'summary' ? (
        <SummaryView
          items={summaryItems}
          expandedMedicine={expandedMedicine}
          expandedItems={expandedItems}
          expandLoading={expandLoading}
          onExpand={handleExpand}
          onAdjust={handleAdjust}
          onDelete={handleDelete}
        />
      ) : (
        <DetailView items={cabinetItems} onAdjust={handleAdjust} onDelete={handleDelete} />
      )}
    </div>
  );
}

// ─── SummaryView ─────────────────────────────────────────────────────────────

function SummaryView({
  items,
  expandedMedicine,
  expandedItems,
  expandLoading,
  onExpand,
  onAdjust,
  onDelete,
}: {
  items: SummaryItem[];
  expandedMedicine: string | null;
  expandedItems: CabinetItem[];
  expandLoading: boolean;
  onExpand: (id: string) => void;
  onAdjust: (id: string, delta: number) => Promise<void>;
  onDelete: (id: string) => void;
}) {
  if (items.length === 0) {
    return (
      <div
        style={{
          background: 'var(--bg-elev)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-md)',
          padding: '48px 24px',
          textAlign: 'center',
          color: 'var(--ink-muted)',
          fontSize: 14,
        }}
      >
        Your cabinet is empty. Add medicines above.
      </div>
    );
  }

  return (
    <div className="cab-grid">
      {items.map((item, idx) => {
        const level = getLevel(item.earliestExpiry);
        const color = vizColor(idx);
        const isExpanded = expandedMedicine === item.medicineId;
        const isWarnExpiry =
          item.earliestExpiry !== null &&
          Math.ceil((new Date(item.earliestExpiry).getTime() - Date.now()) / 86400000) < 60;

        return (
          <div key={item.medicineId} style={{ display: 'flex', flexDirection: 'column' }}>
            <button
              onClick={() => onExpand(item.medicineId)}
              className={`cab-card cab-card--lvl-${level}`}
              style={{ '--c': color } as React.CSSProperties}
            >
              <div className="cab-card__top">
                <div className="cab-card__swatch">
                  <Icon name={iconForForm(item.medicineForm)} size={16} />
                </div>
                <div className="cab-card__meta">
                  <div className="cab-card__name">{item.medicineName}</div>
                  <div className="cab-card__strength">
                    {item.medicineStrength} {item.medicineStrengthUnit}&nbsp;·&nbsp;
                    {FORM_LABELS[item.medicineForm] ?? item.medicineForm}
                  </div>
                </div>
                {level !== 'ok' && (
                  <span
                    className={`mt-pill cab-card__flag ${level === 'critical' ? 'mt-pill--danger' : 'mt-pill--warn'}`}
                  >
                    {level === 'critical' ? 'Expired' : 'Expiring'}
                  </span>
                )}
              </div>

              <div className="cab-card__qty">
                <div className="cab-card__qty-num num">{item.totalQuantity}</div>
                <div className="cab-card__qty-unit">{UNIT_LABELS[item.unit] ?? item.unit}</div>
              </div>

              <ExpiryBar expirationDate={item.earliestExpiry} />

              <div className="cab-card__foot">
                <div>
                  <div className="cab-card__foot-label">Expiry</div>
                  <div
                    className={`cab-card__foot-value num${isWarnExpiry ? ' cab-card__foot-value--warn' : ''}`}
                  >
                    {item.earliestExpiry
                      ? new Date(item.earliestExpiry).toISOString().slice(0, 7)
                      : '—'}
                  </div>
                </div>
                <div>
                  <div className="cab-card__foot-label">Lots</div>
                  <div className="cab-card__foot-value num">{item.itemCount}</div>
                </div>
                <div>
                  <div className="cab-card__foot-label">Items</div>
                  <div className="cab-card__foot-value num">
                    {item.itemCount} {item.itemCount === 1 ? 'item' : 'items'}
                  </div>
                </div>
              </div>

              <div
                aria-hidden="true"
                style={{
                  position: 'absolute',
                  bottom: 8,
                  right: 10,
                  color: 'var(--ink-faint)',
                  transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                  transition: 'transform 0.2s',
                }}
              >
                <Icon name="chevDown" size={14} />
              </div>
            </button>

            {/* Expanded items */}
            {isExpanded && (
              <div className="cab-items" style={{ marginTop: 6, marginBottom: 2 }}>
                {expandLoading ? (
                  <div style={{ padding: '14px 16px' }}>
                    <div
                      style={{
                        height: 40,
                        borderRadius: 'var(--r-sm)',
                        background: 'var(--bg-inset)',
                      }}
                    />
                  </div>
                ) : expandedItems.length === 0 ? (
                  <div
                    style={{
                      padding: '14px 16px',
                      fontSize: 13,
                      color: 'var(--ink-muted)',
                    }}
                  >
                    No active items
                  </div>
                ) : (
                  expandedItems.map((ci) => (
                    <div key={ci._id} className="cab-items__row">
                      <CabinetItemCard item={ci} onAdjust={onAdjust} onDelete={onDelete} />
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── DetailView ───────────────────────────────────────────────────────────────

function DetailView({
  items,
  onAdjust,
  onDelete,
}: {
  items: CabinetItem[];
  onAdjust: (id: string, delta: number) => Promise<void>;
  onDelete: (id: string) => void;
}) {
  if (items.length === 0) {
    return (
      <div
        style={{
          background: 'var(--bg-elev)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-md)',
          padding: '48px 24px',
          textAlign: 'center',
          color: 'var(--ink-muted)',
          fontSize: 14,
        }}
      >
        No items match your filter.
      </div>
    );
  }

  return (
    <div className="cab-list">
      {items.map((item) => (
        <div key={item._id} className="cab-list__row">
          <CabinetItemCard item={item} showMedicineName onAdjust={onAdjust} onDelete={onDelete} />
        </div>
      ))}
    </div>
  );
}

// ─── CabinetItemCard ─────────────────────────────────────────────────────────

function CabinetItemCard({
  item,
  showMedicineName = false,
  onAdjust,
  onDelete,
}: {
  item: CabinetItem;
  showMedicineName?: boolean;
  onAdjust: (id: string, delta: number) => Promise<void>;
  onDelete: (id: string) => void;
}) {
  const [isPending, setIsPending] = useState(false);

  const statusStyle =
    item.status === 'active'
      ? { background: 'var(--ok-soft)', color: 'var(--ok)' }
      : item.status === 'expired'
        ? { background: 'var(--danger-soft)', color: 'var(--danger)' }
        : { background: 'var(--bg-inset)', color: 'var(--ink-muted)' };

  async function handleAdjust(delta: number) {
    if (isPending) return;
    setIsPending(true);
    try {
      await onAdjust(item._id, delta);
    } finally {
      setIsPending(false);
    }
  }

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 12,
        width: '100%',
        minWidth: 0,
        opacity: isPending ? 0.6 : 1,
        pointerEvents: isPending ? 'none' : 'auto',
        transition: 'opacity 0.2s',
      }}
    >
      {/* Left: info */}
      <div style={{ flex: 1, minWidth: 0 }}>
        {showMedicineName && (
          <div
            style={{
              fontSize: 14,
              fontWeight: 500,
              color: 'var(--ink-strong)',
              marginBottom: 2,
            }}
          >
            {item.medicineName}
          </div>
        )}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            fontSize: 13,
            color: 'var(--ink-muted)',
            flexWrap: 'wrap',
          }}
        >
          {showMedicineName && (
            <span>
              {item.medicineStrength} {item.medicineStrengthUnit}&nbsp;
              {FORM_LABELS[item.medicineForm] ?? item.medicineForm}
            </span>
          )}
          {item.medicineProductBrand && (
            <span style={{ color: 'var(--ink-faint)' }}>({item.medicineProductBrand})</span>
          )}
          {item.concentration != null && item.concentrationUnit && (
            <span>
              {item.concentration} {item.concentrationUnit}
            </span>
          )}
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            marginTop: 4,
            fontSize: 13,
          }}
        >
          <span style={{ fontWeight: 600, color: 'var(--ink-strong)' }}>
            {item.quantity} {UNIT_LABELS[item.unit] ?? item.unit}
          </span>
          {item.expirationDate && (
            <span style={{ color: expiryTextColor(item.expirationDate) }}>
              Exp: {formatDate(item.expirationDate)} {daysUntilExpiry(item.expirationDate)}
            </span>
          )}
        </div>
        {item.notes && (
          <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 2 }}>{item.notes}</div>
        )}
      </div>

      {/* Right: status + actions */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
        <span className="mt-pill" style={statusStyle}>
          {/* v8 ignore next */}
          {STATUS_LABELS[item.status] ?? item.status}
        </span>

        {item.status === 'active' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
            <button
              onClick={() => handleAdjust(-1)}
              style={{
                border: '1px solid var(--border)',
                padding: '3px 8px',
                borderRadius: 'var(--r-xs)',
                fontSize: 12,
                fontWeight: 600,
                color: 'var(--ink-muted)',
                background: 'var(--bg-elev)',
                cursor: 'pointer',
                lineHeight: 1.5,
              }}
              title="Take 1"
            >
              -1
            </button>
            <button
              onClick={() => handleAdjust(1)}
              style={{
                border: '1px solid var(--border)',
                padding: '3px 8px',
                borderRadius: 'var(--r-xs)',
                fontSize: 12,
                fontWeight: 600,
                color: 'var(--ink-muted)',
                background: 'var(--bg-elev)',
                cursor: 'pointer',
                lineHeight: 1.5,
              }}
              title="Add 1"
            >
              +1
            </button>
          </div>
        )}

        <button
          onClick={() => onDelete(item._id)}
          style={{
            padding: 5,
            borderRadius: 'var(--r-xs)',
            color: 'var(--ink-faint)',
            background: 'transparent',
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
          }}
          title="Delete"
        >
          <Icon name="trash" size={15} />
        </button>
      </div>
    </div>
  );
}

// ─── AddToCabinetForm ─────────────────────────────────────────────────────────

function AddToCabinetForm({
  householdId,
  onCreated,
  onCancel,
}: {
  householdId: string;
  onCreated: () => void;
  onCancel: () => void;
}) {
  const [medicines, setMedicines] = useState<MedicineOption[]>([]);
  const [formData, setFormData] = useState<CreateCabinetItemInput>({
    medicineId: '',
    quantity: 0,
    unit: DosageUnit.TABLET,
  });
  const [expirationDate, setExpirationDate] = useState('');
  const [notes, setNotes] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [medicineSearch, setMedicineSearch] = useState('');

  useEffect(() => {
    async function fetchMedicines() {
      try {
        const result = await listMedicines(householdId, {
          q: medicineSearch || undefined,
          limit: 50,
        });
        setMedicines(result.data);
      } catch {
        /* empty */
      }
    }
    fetchMedicines();
  }, [householdId, medicineSearch]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    if (!formData.medicineId) {
      setError('Please select a medicine');
      return;
    }
    setSubmitting(true);
    try {
      const payload: CreateCabinetItemInput = {
        ...formData,
        quantity: Number(formData.quantity),
      };
      if (expirationDate) {
        payload.expirationDate = new Date(expirationDate).toISOString();
      }
      if (notes.trim()) {
        payload.notes = notes.trim();
      }
      await createCabinetItem(householdId, payload);
      onCreated();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to add item');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div
      style={{
        marginBottom: 20,
        background: 'var(--bg-elev)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)',
        overflow: 'hidden',
      }}
    >
      {/* Header */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '14px 20px',
          borderBottom: '1px solid var(--border)',
          background: 'var(--bg-inset)',
        }}
      >
        <div
          style={{
            fontFamily: 'var(--font-display)',
            fontSize: 16,
            fontWeight: 500,
            color: 'var(--ink-strong)',
          }}
        >
          Add to Cabinet
        </div>
        <button
          type="button"
          onClick={onCancel}
          style={{
            color: 'var(--ink-muted)',
            padding: 4,
            borderRadius: 'var(--r-xs)',
            cursor: 'pointer',
          }}
          aria-label="Close"
        >
          <Icon name="x" size={16} />
        </button>
      </div>

      {/* Body */}
      <div style={{ padding: '20px' }}>
        {error && (
          <div
            style={{
              marginBottom: 16,
              background: 'var(--danger-soft)',
              border: '1px solid color-mix(in oklab, var(--danger) 25%, var(--danger-soft))',
              borderRadius: 'var(--r-sm)',
              padding: '10px 14px',
              fontSize: 13,
              color: 'var(--danger)',
            }}
          >
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit}>
          {/* Medicine */}
          <div style={{ marginBottom: 16 }}>
            <label className="mt-field-label">Medicine</label>
            <input
              type="text"
              value={medicineSearch}
              onChange={(e) => setMedicineSearch(e.target.value)}
              placeholder="Search medicines..."
              className="mt-field"
              style={{ marginBottom: 8 }}
            />
            <select
              value={formData.medicineId}
              onChange={(e) => {
                const selectedMed = medicines.find((m) => m._id === e.target.value);
                const medForm = selectedMed?.form as MedicineForm | undefined;
                const defUnit = medForm ? defaultUnitForForm(medForm) : DosageUnit.TABLET;
                setFormData({ ...formData, medicineId: e.target.value, unit: defUnit });
              }}
              className="mt-field"
              required
            >
              <option value="">Select a medicine</option>
              {medicines.map((med) => (
                <option key={med._id} value={med._id}>
                  {med.name} ({med.strength} {med.strengthUnit}, {/* v8 ignore next */}
                  {FORM_LABELS[med.form] ?? med.form})
                </option>
              ))}
            </select>
            {medicines.length === 0 && (
              <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 6 }}>
                No medicines found.{' '}
                <Link
                  href="/medicines"
                  style={{ color: 'var(--brand)', textDecoration: 'underline' }}
                >
                  Add medicines first
                </Link>
              </p>
            )}
          </div>

          {/* Qty + Unit */}
          <div
            style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}
          >
            <div>
              <label className="mt-field-label">Quantity</label>
              <input
                type="number"
                required
                min={0}
                step="any"
                value={formData.quantity || ''}
                onChange={(e) => setFormData({ ...formData, quantity: Number(e.target.value) })}
                placeholder="30"
                className="mt-field"
              />
            </div>
            <div>
              <label className="mt-field-label">Unit</label>
              <select
                value={formData.unit}
                onChange={(e) => setFormData({ ...formData, unit: e.target.value as DosageUnit })}
                className="mt-field"
              >
                {(() => {
                  const selectedMed = medicines.find((m) => m._id === formData.medicineId);
                  const units = selectedMed
                    ? allowedUnitsForForm(selectedMed.form as MedicineForm)
                    : Object.values(DosageUnit);
                  return units.map((u) => (
                    <option key={u} value={u}>
                      {/* v8 ignore next */}
                      {UNIT_LABELS[u] ?? u}
                    </option>
                  ));
                })()}
              </select>
            </div>
          </div>

          {/* Expiry + Notes */}
          <div
            style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}
          >
            <div>
              <label className="mt-field-label">Expiration Date (optional)</label>
              <input
                type="date"
                value={expirationDate}
                onChange={(e) => setExpirationDate(e.target.value)}
                className="mt-field"
              />
            </div>
            <div>
              <label className="mt-field-label">Notes (optional)</label>
              <input
                type="text"
                maxLength={1000}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Any notes about this item"
                className="mt-field"
              />
            </div>
          </div>

          {/* Submit */}
          <div style={{ display: 'flex', gap: 10 }}>
            <button type="submit" disabled={submitting} className="mt-btn mt-btn--primary">
              {submitting ? 'Adding...' : 'Add to Cabinet'}
            </button>
            <button type="button" onClick={onCancel} className="mt-btn mt-btn--ghost">
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
