import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useBotStore, type StoreBot } from '../stores/bot.ts';
import { useServerStore } from '../stores/server.ts';
import { useAuthStore } from '../stores/auth.ts';

export function BotStore() {
  const storeBots = useBotStore((s) => s.storeBots);
  const loading = useBotStore((s) => s.loading);
  const error = useBotStore((s) => s.error);
  const fetchStoreBots = useBotStore((s) => s.fetchStoreBots);
  const addToServer = useBotStore((s) => s.addToServer);

  const servers = useServerStore((s) => s.servers);
  const fetchServers = useServerStore((s) => s.fetchServers);
  const currentUserId = useAuthStore((s) => s.user?.id);

  const [addBotId, setAddBotId] = useState<string | null>(null);
  const [selectedServer, setSelectedServer] = useState('');
  const [adding, setAdding] = useState(false);
  const [search, setSearch] = useState('');

  useEffect(() => {
    fetchStoreBots();
    fetchServers();
  }, [fetchStoreBots, fetchServers]);

  const handleAdd = async () => {
    if (!addBotId || !selectedServer) return;
    setAdding(true);
    try {
      await addToServer(addBotId, selectedServer);
      setAddBotId(null);
      setSelectedServer('');
      fetchStoreBots(); // refresh counts
    } catch {
      // error in store
    } finally {
      setAdding(false);
    }
  };

  const filtered = storeBots.filter((b) =>
    b.name.toLowerCase().includes(search.toLowerCase()) ||
    b.description.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="h-full w-full bg-gb-bg p-4 md:p-8 overflow-y-auto">
      <div className="max-w-3xl mx-auto">
        <div className="border border-gb-bg-t p-6">
          <pre className="text-gb-orange font-mono text-center mb-2">
            {'┌──────────────────────────────────┐\n'}
            {'│       === BOT STORE ===          │\n'}
            {'└──────────────────────────────────┘'}
          </pre>
          <p className="text-gb-fg-f font-mono text-xs text-center mb-6">
            browse and add bots to your servers
          </p>

          {error && (
            <p className="text-gb-red text-sm font-mono mb-4">ERR: {error}</p>
          )}

          {/* Search */}
          <div className="mb-6">
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="search bots..."
              className="terminal-input w-full"
            />
          </div>

          {/* Bot list */}
          {loading && storeBots.length === 0 && (
            <p className="text-gb-fg-f font-mono text-sm">[loading...]</p>
          )}
          {!loading && filtered.length === 0 && (
            <p className="text-gb-fg-f font-mono text-sm">[no bots found]</p>
          )}

          <div className="space-y-3">
            {filtered.map((bot) => (
              <StoreBotCard
                key={bot.id}
                bot={bot}
                isOwner={bot.owner_id === currentUserId}
                onAdd={() => { setAddBotId(bot.id); setSelectedServer(''); }}
              />
            ))}
          </div>

          {/* Add to server modal */}
          {addBotId && (
            <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
              <div className="border border-gb-bg-t bg-gb-bg p-6 max-w-md w-full mx-4">
                <p className="text-gb-orange font-mono text-sm mb-4">
                  {'>'} ADD BOT TO SERVER
                </p>
                <select
                  value={selectedServer}
                  onChange={(e) => setSelectedServer(e.target.value)}
                  className="terminal-input w-full mb-4"
                >
                  <option value="">-- select server --</option>
                  {servers.map((s) => (
                    <option key={s.id} value={s.id}>{s.name}</option>
                  ))}
                </select>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={handleAdd}
                    className="terminal-button text-xs"
                    disabled={!selectedServer || adding}
                  >
                    {adding ? '[ADDING...]' : '[ADD]'}
                  </button>
                  <button
                    type="button"
                    onClick={() => { setAddBotId(null); setSelectedServer(''); }}
                    className="text-gb-fg-f hover:text-gb-aqua font-mono text-xs"
                  >
                    [CANCEL]
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Footer */}
          <div className="mt-6 pt-4 border-t border-gb-bg-t flex justify-between">
            <Link to="/" className="text-gb-fg-f hover:text-gb-aqua font-mono text-sm">
              {'<'} [BACK TO CHAT]
            </Link>
            <Link to="/bots/manage" className="text-gb-fg-f hover:text-gb-aqua font-mono text-sm">
              [MY BOTS]
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}

function StoreBotCard({ bot, isOwner, onAdd }: { bot: StoreBot; isOwner: boolean; onAdd: () => void }) {
  return (
    <div className="border border-gb-bg-t p-4">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <p className="text-gb-green font-mono text-sm">
            {bot.avatar && (
              <img
                src={bot.avatar}
                alt=""
                className="inline w-5 h-5 mr-1 align-middle border border-gb-bg-t"
              />
            )}
            [{bot.name}]
            {isOwner && (
              <span className="text-gb-fg-f text-xs ml-2">(yours)</span>
            )}
          </p>
          {bot.description && (
            <p className="text-gb-fg-f font-mono text-xs mt-1">{bot.description}</p>
          )}
        </div>
        <div className="text-right shrink-0">
          <p className="text-gb-aqua font-mono text-xs">
            {bot.server_count} {bot.server_count === 1 ? 'server' : 'servers'}
          </p>
        </div>
      </div>
      <div className="mt-3 flex gap-2">
        <button
          type="button"
          onClick={onAdd}
          className="terminal-button text-xs"
        >
          [ADD TO SERVER]
        </button>
      </div>
    </div>
  );
}
