
import { useState } from 'react';
import { X } from 'lucide-react';
import { newId } from '@/lib/ids';
import { getSystem } from '@/lib/rules';
import type { InventoryItem } from '@/lib/schemas';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { NumberField } from '@/components/ui/NumberField';
import { cn } from '@/lib/cn';
import { SheetSection, type SectionProps } from './common';

const COINS = [
  { key: 'pp', label: 'PP' },
  { key: 'gp', label: 'GP' },
  { key: 'ep', label: 'EP' },
  { key: 'sp', label: 'SP' },
  { key: 'cp', label: 'CP' },
] as const;

export function InventorySection({ c, update }: SectionProps) {
  const [name, setName] = useState('');
  const [qty, setQty] = useState(1);
  const [weight, setWeight] = useState(0);

  const sys = getSystem(c.system);
  const capacity = sys.carryingCapacity({ level: c.level, abilities: c.abilities });
  const totalWeight = c.inventory.reduce((sum, i) => sum + i.quantity * i.weight, 0);
  const encumbered = totalWeight > capacity.encumbered;
  const overMax = totalWeight > capacity.max;

  const addItem = () => {
    if (name.trim() === '') return;
    const item: InventoryItem = {
      id: newId(),
      name: name.trim(),
      quantity: qty,
      weight,
      equipped: false,
      attuned: false,
      description: '',
    };
    update({ inventory: [...c.inventory, item] });
    setName('');
    setQty(1);
    setWeight(0);
  };

  const patchItem = (id: string, patch: Partial<InventoryItem>) => {
    update({ inventory: c.inventory.map((i) => (i.id === id ? { ...i, ...patch } : i)) });
  };
  const removeItem = (id: string) => update({ inventory: c.inventory.filter((i) => i.id !== id) });

  const setCoin = (key: (typeof COINS)[number]['key'], value: number) =>
    update({ currency: { ...c.currency, [key]: value } });

  return (
    <SheetSection title="Inventory & Equipment">
      {/* Currency */}
      <div className="mb-3 flex flex-wrap gap-2">
        {COINS.filter((coin) => coin.key !== 'ep' || c.system === '5e').map((coin) => (
          <label key={coin.key} className="flex items-center gap-1 rounded-md border border-line bg-panel px-2 py-1 text-xs text-muted">
            {coin.label}
            <NumberField
              className="w-16"
              value={c.currency[coin.key]}
              min={0}
              onChange={(v) => setCoin(coin.key, v)}
              aria-label={`${coin.label} coins`}
            />
          </label>
        ))}
      </div>

      {/* Encumbrance */}
      <div className={cn('mb-3 text-sm', overMax ? 'text-danger' : encumbered ? 'text-warning' : 'text-muted')}>
        Carried: <span className="font-medium">{totalWeight.toLocaleString()}</span> / {capacity.max.toLocaleString()} {capacity.unit}
        {overMax ? ' — over maximum!' : encumbered ? ' — encumbered' : ''}
      </div>

      {/* Add item */}
      <div className="mb-3 flex flex-wrap items-end gap-2">
        <label className="flex-1 min-w-40 text-xs text-muted">
          Item
          <Input value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addItem()} placeholder="Longsword" />
        </label>
        <label className="text-xs text-muted">
          Qty
          <NumberField className="w-16" value={qty} min={0} onChange={setQty} aria-label="Quantity" />
        </label>
        <label className="text-xs text-muted">
          Wt
          <NumberField className="w-16" value={weight} min={0} onChange={setWeight} aria-label="Weight" />
        </label>
        <Button variant="primary" onClick={addItem}>Add</Button>
      </div>

      {/* Item list */}
      {c.inventory.length === 0 ? (
        <p className="text-sm text-muted">No items yet.</p>
      ) : (
        <ul className="space-y-1">
          {c.inventory.map((item) => (
            <li key={item.id} className="flex flex-wrap items-center gap-2 rounded-md border border-line bg-panel px-3 py-1.5 text-sm">
              <Input
                className="h-8 min-w-32 flex-1"
                value={item.name}
                onChange={(e) => patchItem(item.id, { name: e.target.value })}
                aria-label="Item name"
              />
              <label className="text-xs text-muted">×<NumberField className="ml-1 w-14 inline-block" value={item.quantity} min={0} onChange={(v) => patchItem(item.id, { quantity: v })} aria-label="Quantity" /></label>
              <label className="text-xs text-muted">{item.weight * item.quantity} {capacity.unit}</label>
              <label className="flex items-center gap-1 text-xs text-muted">
                <input type="checkbox" checked={item.equipped} onChange={(e) => patchItem(item.id, { equipped: e.target.checked })} />
                Equipped
              </label>
              {c.system === '5e' && (
                <label className="flex items-center gap-1 text-xs text-muted">
                  <input type="checkbox" checked={item.attuned} onChange={(e) => patchItem(item.id, { attuned: e.target.checked })} />
                  Attuned
                </label>
              )}
              <Button size="icon" variant="ghost" className="text-danger" onClick={() => removeItem(item.id)} aria-label={`Remove ${item.name}`}><X size={14} aria-hidden /></Button>
            </li>
          ))}
        </ul>
      )}
    </SheetSection>
  );
}
