import { useState } from 'react';
import { X } from 'lucide-react';
import { newId } from '@/lib/ids';
import type { Feat } from '@/lib/schemas';
import { Button } from '@/components/ui/Button';
import { Input, Textarea } from '@/components/ui/Input';
import { SheetSection, type SectionProps } from './common';

/** Feats tracked as first-class records (name + effect) rather than buried in notes. */
export function FeatsSection({ c, update }: SectionProps) {
  const [name, setName] = useState('');

  const add = () => {
    if (name.trim() === '') return;
    const feat: Feat = { id: newId(), name: name.trim(), source: '', description: '' };
    update({ feats: [...c.feats, feat] });
    setName('');
  };
  const patch = (id: string, p: Partial<Feat>) =>
    update({ feats: c.feats.map((f) => (f.id === id ? { ...f, ...p } : f)) });
  const remove = (id: string) => update({ feats: c.feats.filter((f) => f.id !== id) });

  return (
    <SheetSection title="Feats & Features">
      <div className="mb-3 flex items-end gap-2">
        <label className="flex-1 min-w-40 text-xs text-muted">
          Add feat / feature
          <Input value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && add()} placeholder="Great Weapon Master, Oath of Devotion…" />
        </label>
        <Button variant="primary" onClick={add}>Add</Button>
      </div>

      {c.feats.length === 0 ? (
        <p className="text-sm text-muted">No feats or features tracked yet.</p>
      ) : (
        <ul className="space-y-2">
          {c.feats.map((f) => (
            <li key={f.id} className="rounded-md border border-line bg-panel p-2">
              <div className="flex items-center gap-2">
                <Input className="h-8 flex-1 font-medium" value={f.name} onChange={(e) => patch(f.id, { name: e.target.value })} aria-label="Feat name" />
                <Button size="icon" variant="ghost" className="text-danger" onClick={() => remove(f.id)} aria-label={`Remove ${f.name}`}><X size={14} aria-hidden /></Button>
              </div>
              <Textarea className="mt-1 text-xs" rows={2} value={f.description} onChange={(e) => patch(f.id, { description: e.target.value })} placeholder="What it does — kept handy at the table." aria-label={`${f.name} description`} />
            </li>
          ))}
        </ul>
      )}
    </SheetSection>
  );
}
