import { useState, useMemo, type ReactNode } from "react";

interface Stock {
  id: string;
  ticker: string;
  notes: string | null;
  lastDecision: string | null;
  lastJobId: string | null;
  createdAt: string;
  updatedAt: string;
}

interface StockTableProps {
  stocks: Stock[];
  onNotesSave: (ticker: string, notes: string) => Promise<void>;
  saveError: string | null;
}

type SortField = "ticker" | "createdAt" | "updatedAt";
type SortDirection = "asc" | "desc";

function SortHeader({ field, children, sortField, sortDirection, onSort }: {
  field: SortField;
  children: ReactNode;
  sortField: SortField;
  sortDirection: SortDirection;
  onSort: (field: SortField) => void;
}) {
  return (
    <th
      className="text-left py-2 px-3 font-medium text-gray-700 cursor-pointer hover:text-gray-900 select-none"
      onClick={() => onSort(field)}
    >
      {children}
      {sortField === field && <span className="ml-1">{sortDirection === "asc" ? "↑" : "↓"}</span>}
    </th>
  );
}

export default function StockTable({ stocks, onNotesSave, saveError }: StockTableProps) {
  const [search, setSearch] = useState("");
  const [sortField, setSortField] = useState<SortField>("ticker");
  const [sortDirection, setSortDirection] = useState<SortDirection>("asc");
  const [editingTicker, setEditingTicker] = useState<string | null>(null);
  const [editingNotes, setEditingNotes] = useState("");
  const [savingNotes, setSavingNotes] = useState<string | null>(null);
  const [page, setPage] = useState(0);
  const pageSize = 20;

  const filtered = useMemo(() => {
    const q = search.toLowerCase();
    const result = stocks.filter((s) => s.ticker.toLowerCase().includes(q));
    result.sort((a, b) => {
      const aVal = a[sortField] ?? "";
      const bVal = b[sortField] ?? "";
      const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
      return sortDirection === "asc" ? cmp : -cmp;
    });
    return result;
  }, [stocks, search, sortField, sortDirection]);

  const totalPages = Math.ceil(filtered.length / pageSize);
  const paged = filtered.slice(page * pageSize, (page + 1) * pageSize);

  const handleSort = (field: SortField) => {
    setPage(0);
    if (sortField === field) {
      setSortDirection((d) => (d === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  const startEditing = (stock: Stock) => {
    setEditingTicker(stock.ticker);
    setEditingNotes(stock.notes ?? "");
  };

  const saveNotes = async () => {
    if (!editingTicker) return;
    setSavingNotes(editingTicker);
    try {
      await onNotesSave(editingTicker, editingNotes);
      setEditingTicker(null);
    } catch (e) {
      console.error("Failed to save notes:", e);
    } finally {
      setSavingNotes(null);
    }
  };

  if (stocks.length === 0) {
    return (
      <p className="text-gray-500 py-8">No stocks tracked yet. Visit the stocks page to add some.</p>
    );
  }

  return (
    <div className="space-y-6">
      {saveError && (
        <div className="bg-red-50 text-red-700 px-4 py-2 rounded-lg text-sm">{saveError}</div>
      )}

      <div className="flex items-center gap-4">
        <input
          type="text"
          placeholder="Search by ticker..."
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(0); }}
          className="border border-gray-300 rounded-lg px-4 py-2.5 w-64 focus:ring-2 focus:ring-blue-500"
        />
        <span className="text-sm text-gray-500">{filtered.length} stock{filtered.length !== 1 ? "s" : ""}</span>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200">
              <SortHeader field="ticker" sortField={sortField} sortDirection={sortDirection} onSort={handleSort}>Ticker</SortHeader>
              <th className="text-left py-2 px-3 font-medium text-gray-700">Notes</th>
              <th className="text-left py-2 px-3 font-medium text-gray-700">Last Decision</th>
              <th className="text-left py-2 px-3 font-medium text-gray-700">Last Job</th>
              <SortHeader field="createdAt" sortField={sortField} sortDirection={sortDirection} onSort={handleSort}>Created</SortHeader>
              <SortHeader field="updatedAt" sortField={sortField} sortDirection={sortDirection} onSort={handleSort}>Updated</SortHeader>
            </tr>
          </thead>
          <tbody>
            {paged.map((stock) => (
              <tr key={stock.id} className="border-b border-gray-100 hover:bg-gray-50">
                <td className="py-2 px-3 font-medium text-gray-900">{stock.ticker}</td>
                <td className="py-2 px-3">
                   {editingTicker === stock.ticker ? (
                     <div className="flex items-center gap-2">
                       <input
                         type="text"
                         value={editingNotes}
                         onChange={(e) => setEditingNotes(e.target.value)}
                         onKeyDown={(e) => { if (e.key === "Enter") saveNotes(); if (e.key === "Escape") setEditingTicker(null); }}
                         className="flex-1 border border-blue-300 rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500"
                         autoFocus
                       />
                       <button
                         onClick={saveNotes}
                         disabled={savingNotes === stock.ticker}
                         className="text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700 disabled:opacity-50"
                       >
                         {savingNotes === stock.ticker ? "Saving..." : "Save"}
                       </button>
                     </div>
                   ) : (
                    <span
                      className="text-gray-600 cursor-pointer hover:text-gray-900 block py-1"
                      onClick={() => startEditing(stock)}
                    >
                      {stock.notes || <span className="text-gray-400 italic">Click to add notes...</span>}
                    </span>
                  )}
                </td>
                <td className="py-2 px-3">
                  {stock.lastDecision ? (
                    <span className={
                      stock.lastDecision === "buy" ? "text-green-600 font-medium" :
                      stock.lastDecision === "sell" ? "text-red-600 font-medium" : "text-gray-600"
                    }>{stock.lastDecision.toUpperCase()}</span>
                  ) : "-"}
                </td>
                <td className="py-2 px-3 text-gray-600">
                  {stock.lastJobId ? (
                    <span className="text-xs font-mono bg-gray-100 px-2 py-1 rounded">{stock.lastJobId.slice(0, 12)}...</span>
                  ) : "-"}
                </td>
                <td className="py-2 px-3 text-gray-600">{new Date(stock.createdAt).toLocaleDateString()}</td>
                <td className="py-2 px-3 text-gray-600">{new Date(stock.updatedAt).toLocaleDateString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {filtered.length === 0 && (
        <p className="text-gray-500 text-center py-4">No stocks found matching "{search}"</p>
      )}

      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <span className="text-sm text-gray-600">
            Showing {page * pageSize + 1}-{Math.min((page + 1) * pageSize, filtered.length)} of {filtered.length}
          </span>
          <div className="flex gap-2">
            <button
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              disabled={page === 0}
              className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm disabled:opacity-50 hover:bg-gray-50"
            >
              Previous
            </button>
            <button
              onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
              disabled={page >= totalPages - 1}
              className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm disabled:opacity-50 hover:bg-gray-50"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
