'use client';

import { useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useState } from 'react';
import { ArrowRight, Eye, Plus, Trash2 } from 'lucide-react';
import Link from 'next/link';
import { AppShell } from '@/components/shell/app-shell';
import { Panel } from '@/components/ui/panel';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
import { useAuthGuard } from '@/hooks/use-auth-guard';
import { deleteWatchlistItem, queueFilingSync, upsertWatchlistItem } from '@/lib/api';
import type { WatchlistItem } from '@/lib/types';
import { queryKeys } from '@/lib/query/keys';
import { watchlistQueryOptions } from '@/lib/query/options';

type FormState = {
  ticker: string;
  companyName: string;
  sector: string;
  category: string;
  tags: string;
};

function parseTagsInput(input: string) {
  const unique = new Set<string>();

  for (const segment of input.split(',')) {
    const tag = segment.trim();
    if (!tag) {
      continue;
    }

    unique.add(tag);
  }

  return [...unique];
}

export default function WatchlistPage() {
  const { isPending, isAuthenticated } = useAuthGuard();
  const queryClient = useQueryClient();
  const { prefetchResearchTicker } = useLinkPrefetch();

  const [items, setItems] = useState<WatchlistItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>({
    ticker: '',
    companyName: '',
    sector: '',
    category: '',
    tags: ''
  });

  const loadWatchlist = useCallback(async () => {
    const options = watchlistQueryOptions();

    if (!queryClient.getQueryData(options.queryKey)) {
      setLoading(true);
    }

    setError(null);

    try {
      const response = await queryClient.ensureQueryData(options);
      setItems(response.items);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load watchlist');
    } finally {
      setLoading(false);
    }
  }, [queryClient]);

  useEffect(() => {
    if (!isPending && isAuthenticated) {
      void loadWatchlist();
    }
  }, [isPending, isAuthenticated, loadWatchlist]);

  const submit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await upsertWatchlistItem({
        ticker: form.ticker.toUpperCase(),
        companyName: form.companyName,
        sector: form.sector || undefined,
        category: form.category || undefined,
        tags: parseTagsInput(form.tags)
      });

      setForm({
        ticker: '',
        companyName: '',
        sector: '',
        category: '',
        tags: ''
      });
      void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
      await loadWatchlist();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save watchlist item');
    }
  };

  const queueSync = async (item: WatchlistItem) => {
    try {
      await queueFilingSync({
        ticker: item.ticker,
        limit: 20,
        category: item.category ?? undefined,
        tags: item.tags.length > 0 ? item.tags : undefined
      });
      void queryClient.invalidateQueries({ queryKey: queryKeys.recentTasks(20) });
      void queryClient.invalidateQueries({ queryKey: ['filings'] });
    } catch (err) {
      setError(err instanceof Error ? err.message : `Failed to queue sync for ${item.ticker}`);
    }
  };

  if (isPending || !isAuthenticated) {
    return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading watchlist terminal...</div>;
  }

  return (
    <AppShell
      title="Watchlist"
      subtitle="Track symbols, company context, and trigger filing ingestion jobs from one surface."
    >
      <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.6fr_1fr]">
        <Panel title="Symbols" subtitle="Your monitored universe.">
          {error ? <p className="text-sm text-[#ffb5b5]">{error}</p> : null}
          {loading ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">Loading watchlist...</p>
          ) : items.length === 0 ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">No symbols yet. Add one from the right panel.</p>
          ) : (
            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              {items.map((item) => (
                <article key={item.id} className="rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">
                        {item.sector ?? 'Unclassified'}
                        {item.category ? ` · ${item.category}` : ''}
                      </p>
                      <h3 className="mt-1 text-xl font-semibold text-[color:var(--terminal-bright)]">{item.ticker}</h3>
                      <p className="mt-1 text-sm text-[color:var(--terminal-muted)]">{item.company_name}</p>
                      {item.tags.length > 0 ? (
                        <div className="mt-2 flex flex-wrap gap-1">
                          {item.tags.map((tag) => (
                            <span
                              key={`${item.id}-${tag}`}
                              className="rounded border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]"
                            >
                              {tag}
                            </span>
                          ))}
                        </div>
                      ) : null}
                    </div>
                    <Eye className="size-4 text-[color:var(--accent)]" />
                  </div>

                  <div className="mt-4 flex flex-wrap items-center gap-2">
                    <Button variant="secondary" className="px-2 py-1 text-xs" onClick={() => void queueSync(item)}>
                      Sync filings
                    </Button>
                    <Link
                      href={`/filings?ticker=${item.ticker}`}
                      onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                      onFocus={() => prefetchResearchTicker(item.ticker)}
                      className="inline-flex items-center gap-1 text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
                    >
                      Open stream
                      <ArrowRight className="size-3" />
                    </Link>
                    <Link
                      href={`/analysis?ticker=${item.ticker}`}
                      onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                      onFocus={() => prefetchResearchTicker(item.ticker)}
                      className="inline-flex items-center gap-1 text-xs text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
                    >
                      Analyze
                      <ArrowRight className="size-3" />
                    </Link>
                    <Button
                      variant="danger"
                      className="ml-auto px-2 py-1 text-xs"
                      onClick={async () => {
                        try {
                          await deleteWatchlistItem(item.id);
                          void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
                          await loadWatchlist();
                        } catch (err) {
                          setError(err instanceof Error ? err.message : 'Failed to remove symbol');
                        }
                      }}
                    >
                      <Trash2 className="size-3" />
                      Remove
                    </Button>
                  </div>
                </article>
              ))}
            </div>
          )}
        </Panel>

        <Panel title="Add Symbol" subtitle="Create or update a watchlist item.">
          <form onSubmit={submit} className="space-y-3">
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Ticker</label>
              <Input value={form.ticker} onChange={(event) => setForm((prev) => ({ ...prev, ticker: event.target.value.toUpperCase() }))} required />
            </div>
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Company Name</label>
              <Input value={form.companyName} onChange={(event) => setForm((prev) => ({ ...prev, companyName: event.target.value }))} required />
            </div>
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Sector</label>
              <Input value={form.sector} onChange={(event) => setForm((prev) => ({ ...prev, sector: event.target.value }))} />
            </div>
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Category</label>
              <Input value={form.category} onChange={(event) => setForm((prev) => ({ ...prev, category: event.target.value }))} placeholder="e.g. Core, Speculative, Watch only" />
            </div>
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Tags</label>
              <Input value={form.tags} onChange={(event) => setForm((prev) => ({ ...prev, tags: event.target.value }))} placeholder="Comma-separated tags" />
            </div>
            <Button type="submit" className="w-full">
              <Plus className="size-4" />
              Save symbol
            </Button>
          </form>
        </Panel>
      </div>
    </AppShell>
  );
}
