'use client';
import { useState } from 'react';
import { AccountCard } from './AccountCard';

interface Account {
  id: string;
  jid: string;
  displayName: string | null;
  status: string;
  platform: string;
}

export function AccountsList({ initialAccounts }: { initialAccounts: Account[] }) {
  const [accounts, setAccounts] = useState<Account[]>(initialAccounts);
  const [displayName, setDisplayName] = useState('');

  async function handleAdd() {
    try {
      const res = await fetch('/api/accounts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ displayName: displayName || undefined }),
      });
      if (!res.ok) return;
      const account: Account = await res.json();
      setAccounts((prev) => [...prev, account]);
      setDisplayName('');
    } catch {}
  }

  return (
    <div>
      <div className="flex gap-2 mb-6">
        <input
          type="text"
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
          placeholder="Display name (optional)"
          className="flex-1 border rounded px-3 py-2 text-sm"
        />
        <button
          onClick={handleAdd}
          className="bg-blue-600 text-white rounded px-4 py-2 text-sm hover:bg-blue-700"
        >
          Add Account
        </button>
      </div>

      {accounts.length === 0 ? (
        <p className="text-gray-500">No accounts yet. Add one above to get started.</p>
      ) : (
        <div className="flex flex-col gap-3">
          {accounts.map((a) => (
            <AccountCard key={a.id} account={a} />
          ))}
        </div>
      )}
    </div>
  );
}
