'use client';

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

type FormState = {
  ticker: string;
  companyName: string;
  sector: string;
  category: string;
  status: CoverageStatus;
  priority: CoveragePriority;
  tags: string;
};

const STATUS_OPTIONS: Array<{ value: CoverageStatus; label: string }> = [
  { value: 'backlog', label: 'Backlog' },
  { value: 'active', label: 'Active' },
  { value: 'watch', label: 'Watch' },
  { value: 'archive', label: 'Archive' }
];

const PRIORITY_OPTIONS: Array<{ value: CoveragePriority; label: string }> = [
  { value: 'high', label: 'High' },
  { value: 'medium', label: 'Medium' },
  { value: 'low', label: 'Low' }
];

const EMPTY_FORM: FormState = {
  ticker: '',
  companyName: '',
  sector: '',
  category: '',
  status: 'backlog',
  priority: 'medium',
  tags: ''
};

const SELECT_CLASS_NAME = 'min-h-11 w-full rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2 text-sm text-[color:var(--terminal-bright)] outline-none transition focus:border-[color:var(--line-strong)] focus:shadow-[0_0_0_3px_var(--focus-ring)]';

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];
}

function formatDateTime(value: string | null) {
  if (!value) {
    return 'Not reviewed';
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }

  return format(parsed, 'MMM dd, yyyy · HH:mm');
}

function formatDateOnly(value: string | null) {
  if (!value) {
    return 'No filings';
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }

  return format(parsed, 'MMM dd, yyyy');
}

function normalizeSearchValue(value: string) {
  return value.trim().toLowerCase();
}

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 [saving, setSaving] = useState(false);
  const [search, setSearch] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [editingItemId, setEditingItemId] = useState<number | null>(null);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);

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

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

    setError(null);

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

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

  const filteredItems = useMemo(() => {
    const normalizedSearch = normalizeSearchValue(search);
    if (!normalizedSearch) {
      return items;
    }

    return items.filter((item) => {
      const haystack = [
        item.ticker,
        item.company_name,
        item.sector ?? '',
        item.category ?? '',
        item.status,
        item.priority,
        ...item.tags
      ].join(' ').toLowerCase();

      return haystack.includes(normalizedSearch);
    });
  }, [items, search]);

  const resetForm = useCallback(() => {
    setEditingItemId(null);
    setForm(EMPTY_FORM);
  }, []);

  const beginEdit = useCallback((item: WatchlistItem) => {
    setEditingItemId(item.id);
    setForm({
      ticker: item.ticker,
      companyName: item.company_name,
      sector: item.sector ?? '',
      category: item.category ?? '',
      status: item.status,
      priority: item.priority,
      tags: item.tags.join(', ')
    });
  }, []);

  const invalidateCoverageQueries = useCallback((ticker?: string) => {
    void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
    if (ticker) {
      const normalizedTicker = ticker.trim().toUpperCase();
      void queryClient.invalidateQueries({ queryKey: queryKeys.companyAnalysis(normalizedTicker) });
      void queryClient.invalidateQueries({ queryKey: queryKeys.researchJournal(normalizedTicker) });
    }
  }, [queryClient]);

  const saveCoverage = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSaving(true);
    setError(null);

    try {
      const payload = {
        companyName: form.companyName.trim(),
        sector: form.sector.trim() || undefined,
        category: form.category.trim() || undefined,
        status: form.status,
        priority: form.priority,
        tags: parseTagsInput(form.tags)
      };

      if (editingItemId === null) {
        await upsertWatchlistItem({
          ticker: form.ticker.trim().toUpperCase(),
          ...payload
        });
      } else {
        await updateWatchlistItem(editingItemId, payload);
      }

      invalidateCoverageQueries(form.ticker);
      await loadCoverage();
      resetForm();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save coverage item');
    } finally {
      setSaving(false);
    }
  };

  const updateCoverageInline = async (
    item: WatchlistItem,
    patch: {
      status?: CoverageStatus;
      priority?: CoveragePriority;
      lastReviewedAt?: string;
    }
  ) => {
    try {
      await updateWatchlistItem(item.id, {
        status: patch.status,
        priority: patch.priority,
        lastReviewedAt: patch.lastReviewedAt
      });
      invalidateCoverageQueries(item.ticker);
      await loadCoverage();
    } catch (err) {
      setError(err instanceof Error ? err.message : `Failed to update ${item.ticker}`);
    }
  };

  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: queryKeys.filings(item.ticker, 120) });
    } catch (err) {
      setError(err instanceof Error ? err.message : `Failed to queue filing 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 coverage terminal...</div>;
  }

  return (
    <AppShell
      title="Coverage"
      subtitle="Track research status, priorities, filing recency, and handoff into company analysis."
    >
      <div className="grid grid-cols-1 gap-6 xl:grid-cols-[1.8fr_1fr]">
        <Panel
          title="Coverage Board"
          subtitle={`${items.length} tracked companies across backlog, active work, and archive.`}
          variant="surface"
          actions={(
            <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
              <Input
                value={search}
                aria-label="Search coverage"
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Search ticker, company, tag, sector..."
                className="w-full sm:min-w-[18rem]"
              />
              <Button
                variant="secondary"
                className="w-full sm:w-auto"
                onClick={() => {
                  void queryClient.invalidateQueries({ queryKey: queryKeys.watchlist() });
                  void loadCoverage();
                }}
              >
                <RefreshCcw className="size-4" />
                Refresh
              </Button>
            </div>
          )}
        >
          {error ? <p className="text-sm text-[#ffb5b5]">{error}</p> : null}
          {loading ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">Loading coverage...</p>
          ) : filteredItems.length === 0 ? (
            <p className="text-sm text-[color:var(--terminal-muted)]">No coverage items match the current search.</p>
          ) : (
            <div className="space-y-3">
              <div className="space-y-3 lg:hidden">
                {filteredItems.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 flex-wrap items-start justify-between gap-3">
                      <div>
                        <div className="font-medium text-[color:var(--terminal-bright)]">{item.ticker}</div>
                        <div className="text-sm text-[color:var(--terminal-bright)]">{item.company_name}</div>
                        <div className="text-xs text-[color:var(--terminal-muted)]">
                          {item.sector ?? 'Unclassified'}
                          {item.category ? ` · ${item.category}` : ''}
                        </div>
                      </div>
                      <div className="text-right text-xs text-[color:var(--terminal-muted)]">
                        <p>Last filing</p>
                        <p className="mt-1 text-[color:var(--terminal-bright)]">{formatDateOnly(item.latest_filing_date)}</p>
                      </div>
                    </div>

                    <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <div>
                        <label className="mb-1 block text-[10px] uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">Status</label>
                        <select
                          aria-label={`${item.ticker} status`}
                          className={SELECT_CLASS_NAME}
                          value={item.status}
                          onChange={(event) => {
                            void updateCoverageInline(item, {
                              status: event.target.value as CoverageStatus
                            });
                          }}
                        >
                          {STATUS_OPTIONS.map((option) => (
                            <option key={option.value} value={option.value}>
                              {option.label}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="mb-1 block text-[10px] uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">Priority</label>
                        <select
                          aria-label={`${item.ticker} priority`}
                          className={SELECT_CLASS_NAME}
                          value={item.priority}
                          onChange={(event) => {
                            void updateCoverageInline(item, {
                              priority: event.target.value as CoveragePriority
                            });
                          }}
                        >
                          {PRIORITY_OPTIONS.map((option) => (
                            <option key={option.value} value={option.value}>
                              {option.label}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <div className="mt-3 flex flex-wrap gap-1">
                      {item.tags.length > 0 ? item.tags.map((tag) => (
                        <span
                          key={`${item.id}-${tag}`}
                          className="rounded border border-[color:var(--line-weak)] bg-[color:var(--panel)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]"
                        >
                          {tag}
                        </span>
                      )) : <span className="text-xs text-[color:var(--terminal-muted)]">No tags</span>}
                    </div>

                    <p className="mt-3 text-xs text-[color:var(--terminal-muted)]">Last reviewed: {formatDateTime(item.last_reviewed_at)}</p>

                    <div className="mt-3 flex flex-wrap items-center gap-2">
                      <Link
                        href={`/analysis?ticker=${item.ticker}`}
                        onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                        onFocus={() => prefetchResearchTicker(item.ticker)}
                        className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                      >
                        Analyze
                        <ArrowRight className="size-3" />
                      </Link>
                      <Link
                        href={`/financials?ticker=${item.ticker}`}
                        onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                        onFocus={() => prefetchResearchTicker(item.ticker)}
                        className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                      >
                        Financials
                      </Link>
                      <Link
                        href={`/filings?ticker=${item.ticker}`}
                        onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                        onFocus={() => prefetchResearchTicker(item.ticker)}
                        className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                      >
                        Filings
                      </Link>
                    </div>

                    <div className="mt-3 grid grid-cols-2 gap-2">
                      <Button variant="secondary" className="px-2 py-1 text-xs" onClick={() => void queueSync(item)}>
                        Sync
                      </Button>
                      <Button
                        variant="ghost"
                        className="px-2 py-1 text-xs"
                        onClick={() => {
                          void updateCoverageInline(item, {
                            lastReviewedAt: new Date().toISOString()
                          });
                        }}
                      >
                        <CalendarClock className="size-3" />
                        Review
                      </Button>
                      <Button
                        variant="ghost"
                        className="px-2 py-1 text-xs"
                        onClick={() => beginEdit(item)}
                      >
                        <SquarePen className="size-3" />
                        Edit
                      </Button>
                      <Button
                        variant="danger"
                        className="px-2 py-1 text-xs"
                        onClick={async () => {
                          try {
                            await deleteWatchlistItem(item.id);
                            invalidateCoverageQueries(item.ticker);
                            await loadCoverage();
                            if (editingItemId === item.id) {
                              resetForm();
                            }
                          } catch (err) {
                            setError(err instanceof Error ? err.message : `Failed to remove ${item.ticker}`);
                          }
                        }}
                      >
                        <Trash2 className="size-3" />
                        Remove
                      </Button>
                    </div>
                  </article>
                ))}
              </div>

              <div className="data-table-wrap hidden lg:block">
                <table className="data-table min-w-[1120px]">
                  <thead>
                    <tr>
                      <th>Company</th>
                      <th>Status</th>
                      <th>Priority</th>
                      <th>Tags</th>
                      <th>Last Filing</th>
                      <th>Last Reviewed</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredItems.map((item) => (
                      <tr key={item.id}>
                        <td>
                          <div className="font-medium text-[color:var(--terminal-bright)]">{item.ticker}</div>
                          <div className="text-sm text-[color:var(--terminal-bright)]">{item.company_name}</div>
                          <div className="text-xs text-[color:var(--terminal-muted)]">
                            {item.sector ?? 'Unclassified'}
                            {item.category ? ` · ${item.category}` : ''}
                          </div>
                        </td>
                        <td>
                          <select
                            aria-label={`${item.ticker} status`}
                            className={SELECT_CLASS_NAME}
                            value={item.status}
                            onChange={(event) => {
                              void updateCoverageInline(item, {
                                status: event.target.value as CoverageStatus
                              });
                            }}
                          >
                            {STATUS_OPTIONS.map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </select>
                        </td>
                        <td>
                          <select
                            aria-label={`${item.ticker} priority`}
                            className={SELECT_CLASS_NAME}
                            value={item.priority}
                            onChange={(event) => {
                              void updateCoverageInline(item, {
                                priority: event.target.value as CoveragePriority
                              });
                            }}
                          >
                            {PRIORITY_OPTIONS.map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </select>
                        </td>
                        <td>
                          {item.tags.length > 0 ? (
                            <div className="flex max-w-[18rem] 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>
                          ) : (
                            <span className="text-xs text-[color:var(--terminal-muted)]">No tags</span>
                          )}
                        </td>
                        <td>{formatDateOnly(item.latest_filing_date)}</td>
                        <td>{formatDateTime(item.last_reviewed_at)}</td>
                        <td>
                          <div className="flex flex-wrap items-center gap-2">
                            <Link
                              href={`/analysis?ticker=${item.ticker}`}
                              onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                              onFocus={() => prefetchResearchTicker(item.ticker)}
                              className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                            >
                              Analyze
                              <ArrowRight className="size-3" />
                            </Link>
                            <Link
                              href={`/research?ticker=${item.ticker}`}
                              onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                              onFocus={() => prefetchResearchTicker(item.ticker)}
                              className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                            >
                              Research
                            </Link>
                            <Link
                              href={`/financials?ticker=${item.ticker}`}
                              onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                              onFocus={() => prefetchResearchTicker(item.ticker)}
                              className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                            >
                              Financials
                            </Link>
                            <Link
                              href={`/filings?ticker=${item.ticker}`}
                              onMouseEnter={() => prefetchResearchTicker(item.ticker)}
                              onFocus={() => prefetchResearchTicker(item.ticker)}
                              className="inline-flex items-center gap-1 rounded-md border border-[color:var(--line-weak)] px-2 py-1 text-xs text-[color:var(--accent)] transition hover:border-[color:var(--line-strong)] hover:text-[color:var(--accent-strong)]"
                            >
                              Filings
                            </Link>
                            <Button variant="secondary" className="px-2 py-1 text-xs" onClick={() => void queueSync(item)}>
                              Sync
                            </Button>
                            <Button
                              variant="ghost"
                              className="px-2 py-1 text-xs"
                              onClick={() => {
                                void updateCoverageInline(item, {
                                  lastReviewedAt: new Date().toISOString()
                                });
                              }}
                            >
                              <CalendarClock className="size-3" />
                              Review
                            </Button>
                            <Button
                              variant="ghost"
                              className="px-2 py-1 text-xs"
                              onClick={() => beginEdit(item)}
                            >
                              <SquarePen className="size-3" />
                              Edit
                            </Button>
                            <Button
                              variant="danger"
                              className="px-2 py-1 text-xs"
                              onClick={async () => {
                                try {
                                  await deleteWatchlistItem(item.id);
                                  invalidateCoverageQueries(item.ticker);
                                  await loadCoverage();
                                  if (editingItemId === item.id) {
                                    resetForm();
                                  }
                                } catch (err) {
                                  setError(err instanceof Error ? err.message : `Failed to remove ${item.ticker}`);
                                }
                              }}
                            >
                              <Trash2 className="size-3" />
                              Remove
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </Panel>

        <Panel
          title={editingItemId === null ? 'Add Coverage' : 'Edit Coverage'}
          subtitle={editingItemId === null ? 'Create a new company coverage record.' : 'Update metadata, priority, and workflow status.'}
          variant="surface"
        >
          <form onSubmit={saveCoverage} 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}
                aria-label="Coverage ticker"
                disabled={editingItemId !== null}
                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}
                aria-label="Coverage company name"
                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}
                aria-label="Coverage 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}
                aria-label="Coverage category"
                onChange={(event) => setForm((prev) => ({ ...prev, category: event.target.value }))}
                placeholder="Core, cyclical, event-driven..."
              />
            </div>
            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              <div>
                <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Status</label>
                <select
                  aria-label="Coverage status"
                  className={SELECT_CLASS_NAME}
                  value={form.status}
                  onChange={(event) => setForm((prev) => ({ ...prev, status: event.target.value as CoverageStatus }))}
                >
                  {STATUS_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Priority</label>
                <select
                  aria-label="Coverage priority"
                  className={SELECT_CLASS_NAME}
                  value={form.priority}
                  onChange={(event) => setForm((prev) => ({ ...prev, priority: event.target.value as CoveragePriority }))}
                >
                  {PRIORITY_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            <div>
              <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Tags</label>
              <Input
                value={form.tags}
                aria-label="Coverage tags"
                onChange={(event) => setForm((prev) => ({ ...prev, tags: event.target.value }))}
                placeholder="Comma-separated tags"
              />
            </div>
            <div className="flex flex-wrap gap-2">
              <Button type="submit" className="w-full sm:flex-1" disabled={saving}>
                <Plus className="size-4" />
                {saving ? 'Saving...' : editingItemId === null ? 'Save coverage' : 'Update coverage'}
              </Button>
              {editingItemId !== null ? (
                <Button type="button" variant="ghost" className="w-full sm:w-auto" onClick={resetForm}>
                  Clear
                </Button>
              ) : null}
            </div>
          </form>
        </Panel>
      </div>
    </AppShell>
  );
}
