import { Plus, Search } from 'lucide-react';
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAccounts } from '@/hooks/useAccounts';
import { AccountCard } from './AccountCard';
import { AccountDetail } from './AccountDetail';
import { Input } from '@/components/ui/input';

export function AccountList() {
  const { accountId } = useParams<{ accountId?: string }>();
  const navigate = useNavigate();
  const { accounts, create, update, remove } = useAccounts();
  const [search, setSearch] = useState('');

  const selected = accountId ? accounts.find((a) => a.id === accountId) || null : null;

  const filtered = accounts.filter((a) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return a.name.toLowerCase().includes(q) || (a.description || '').toLowerCase().includes(q);
  });

  const handleCreate = async () => {
    const name = `新账号 ${accounts.length + 1}`;
    const acc = await create({ name, pipeline: 'image-video', defaultFormat: '9:16', imageModel: 'gemini', videoModel: 'veo3-fast' });
    if (acc?.id) navigate(`/accounts/${acc.id}`);
  };

  // In detail view
  if (selected) {
    return (
      <AccountDetail
        account={selected}
        onSave={(data) => update(selected.id, data)}
        onDelete={() => remove(selected.id).then(() => navigate('/accounts'))}
        onBack={() => navigate('/accounts')}
      />
    );
  }

  // Card grid view
  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-6 py-4 border-b border-zinc-200 bg-white flex-shrink-0">
        <div className="flex items-center gap-3">
          <h1 className="text-base font-semibold text-zinc-800">账号管理</h1>
          <div className="relative">
            <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-400" />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="搜索账号..."
              className="pl-8 h-8 w-48 text-xs bg-zinc-50 border-zinc-200"
            />
          </div>
        </div>
        <button
          onClick={handleCreate}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors"
        >
          <Plus size={14} />
          新建账号
        </button>
      </div>

      {/* Grid */}
      <div className="flex-1 overflow-auto p-6">
        {filtered.length > 0 ? (
          <div className="grid grid-cols-3 gap-4">
            {filtered.map((a) => (
              <AccountCard
                key={a.id}
                account={a}
                isSelected={a.id === accountId}
                onClick={() => navigate(`/accounts/${a.id}`)}
              />
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center h-full text-zinc-400">
            <p className="text-sm">{search ? '没有匹配的账号' : '暂无账号'}</p>
            {!search && (
              <button onClick={handleCreate} className="mt-2 text-xs text-indigo-600 hover:underline">
                创建第一个账号
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
