import { useEffect, useState } from 'react';
import { api } from '../lib/api.ts';

interface ListItem {
  id: string;
  channel_id: string;
  creator_id: string;
  title: string;
  status: string;
  position: number;
  created_at: string;
  updated_at: string;
}

interface ListViewProps {
  channelId: string;
  channelName: string;
}

export function ListView({ channelId, channelName }: ListViewProps) {
  const [items, setItems] = useState<ListItem[]>([]);
  const [newTitle, setNewTitle] = useState('');

  useEffect(() => {
    api.get<ListItem[]>(`/channels/${channelId}/items`)
      .then((data) => setItems(Array.isArray(data) ? data : []));
  }, [channelId]);

  const addItem = async () => {
    if (!newTitle.trim()) return;
    const it = await api.post<ListItem>(`/channels/${channelId}/items`, { title: newTitle });
    setItems((prev) => [...prev, it]);
    setNewTitle('');
  };

  const toggleStatus = async (it: ListItem) => {
    const next = it.status === 'done' ? 'todo' : it.status === 'in_progress' ? 'done' : 'in_progress';
    const updated = await api.patch<ListItem>(`/channels/items/${it.id}`, { status: next });
    setItems((prev) => prev.map((x) => x.id === updated.id ? updated : x));
  };

  const deleteItem = async (id: string) => {
    await api.delete(`/channels/items/${id}`);
    setItems((prev) => prev.filter((x) => x.id !== id));
  };

  const todo = items.filter((x) => x.status === 'todo');
  const inProgress = items.filter((x) => x.status === 'in_progress');
  const done = items.filter((x) => x.status === 'done');

  const col = (list: ListItem[], label: string, color: string) => (
    <div className="flex-1 min-w-0 flex flex-col">
      <div className={`text-xs font-bold font-mono p-2 ${color} border-b border-gb-bg-t`}>
        {label} ({list.length})
      </div>
      <div className="flex-1 overflow-y-auto p-1 space-y-1">
        {list.map((it) => (
          <div key={it.id} className="bg-gb-bg-t rounded p-2 text-xs font-mono group">
            <div className="flex items-start gap-2">
              <button
                onClick={() => toggleStatus(it)}
                className={`mt-0.5 shrink-0 w-4 h-4 rounded border ${it.status === 'done' ? 'bg-gb-orange border-gb-orange' : 'border-gb-fg-f'}`}
              >
                {it.status === 'done' && <span className="flex items-center justify-center text-gb-bg text-[10px]">✓</span>}
              </button>
              <span className={`flex-1 ${it.status === 'done' ? 'line-through text-gb-fg-f' : 'text-gb-fg'}`}>{it.title}</span>
              <button onClick={() => deleteItem(it.id)} className="text-gb-fg-f hover:text-gb-red opacity-0 group-hover:opacity-100">✕</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="flex flex-col h-full bg-gb-bg">
      <div className="terminal-border border-t-0 border-x-0 px-3 py-2 text-gb-fg-s flex items-center justify-between">
        <span>☑ {channelName}</span>
      </div>
      <div className="p-3 border-b border-gb-bg-t font-mono text-xs flex items-center gap-2">
        <input
          value={newTitle}
          onChange={(e) => setNewTitle(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && addItem()}
          placeholder="add item..."
          className="terminal-input flex-1"
        />
        <button onClick={addItem} disabled={!newTitle.trim()} className="px-2 py-1 bg-gb-orange text-gb-bg disabled:opacity-50">[ADD]</button>
      </div>
      <div className="flex-1 flex min-h-0">
        {col(todo, 'TODO', 'text-gb-fg')}
        {col(inProgress, 'DOING', 'text-gb-blue')}
        {col(done, 'DONE', 'text-gb-fg-f')}
      </div>
    </div>
  );
}
