'use client';

import { useSession } from '@/lib/better-auth';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import Link from 'next/link';

export default function WatchlistPage() {
  const { data: session, isPending } = useSession();
  const router = useRouter();
  const [watchlist, setWatchlist] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newStock, setNewStock] = useState({ ticker: '', company_name: '', sector: '' });

  useEffect(() => {
    if (!isPending && !session) {
      router.push('/auth/signin');
      return;
    }

    if (session?.user) {
      fetchWatchlist(session.user.id);
    }
  }, [session, isPending, router]);

  const fetchWatchlist = async (userId: string) => {
    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist/${userId}`);
      const data = await response.json();
      setWatchlist(data);
    } catch (error) {
      console.error('Error fetching watchlist:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddStock = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: session?.user?.id,
          ticker: newStock.ticker.toUpperCase(),
          company_name: newStock.company_name,
          sector: newStock.sector
        })
      });

      setShowAddModal(false);
      setNewStock({ ticker: '', company_name: '', sector: '' });
      fetchWatchlist(session?.user?.id);
    } catch (error) {
      console.error('Error adding stock:', error);
    }
  };

  const handleDeleteStock = async (id: number) => {
    if (!confirm('Are you sure you want to remove this stock from watchlist?')) return;

    try {
      await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/watchlist/${id}`, {
        method: 'DELETE'
      });

      fetchWatchlist(session?.user?.id);
    } catch (error) {
      console.error('Error deleting stock:', error);
    }
  };

  if (loading) {
    return <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 flex items-center justify-center">Loading...</div>;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white">
      <nav className="border-b border-slate-700 bg-slate-900/50 backdrop-blur">
        <div className="container mx-auto px-4 py-4 flex justify-between items-center">
          <Link href="/" className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
            Fiscal Clone
          </Link>
          <div className="flex gap-4">
            <Link href="/filings" className="hover:text-blue-400 transition">
              Filings
            </Link>
            <Link href="/portfolio" className="hover:text-blue-400 transition">
              Portfolio
            </Link>
            <Link href="/watchlist" className="hover:text-blue-400 transition">
              Watchlist
            </Link>
          </div>
        </div>
      </nav>

      <main className="container mx-auto px-4 py-8">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-3xl font-bold">Watchlist</h1>
          <button
            onClick={() => setShowAddModal(true)}
            className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
          >
            + Add Stock
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {watchlist.map((stock: any) => (
            <div key={stock.id} className="bg-slate-800/50 rounded-lg p-6 border border-slate-700 hover:border-slate-600 transition">
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h3 className="text-2xl font-bold">{stock.ticker}</h3>
                  <p className="text-slate-400">{stock.company_name}</p>
                </div>
                <button
                  onClick={() => handleDeleteStock(stock.id)}
                  className="text-red-400 hover:text-red-300 transition"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
              {stock.sector && (
                <div className="inline-block bg-purple-500/20 text-purple-400 px-3 py-1 rounded-full text-sm">
                  {stock.sector}
                </div>
              )}
              <div className="mt-4 flex gap-2">
                <Link
                  href={`/filings?ticker=${stock.ticker}`}
                  className="flex-1 bg-slate-700 hover:bg-slate-600 text-white py-2 rounded-lg text-center transition"
                >
                  Filings
                </Link>
                <Link
                  href={`/portfolio/add?ticker=${stock.ticker}`}
                  className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-center transition"
                >
                  Add to Portfolio
                </Link>
              </div>
            </div>
          ))}

          {watchlist.length === 0 && (
            <div className="col-span-full text-center py-12 bg-slate-800/50 rounded-lg border border-slate-700">
              <p className="text-slate-400 text-lg mb-4">Your watchlist is empty</p>
              <p className="text-slate-500 text-sm">
                Add stocks to track their SEC filings and monitor performance
              </p>
            </div>
          )}
        </div>
      </main>

      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4">
          <div className="bg-slate-800 rounded-lg p-6 border border-slate-700 max-w-md w-full">
            <h2 className="text-2xl font-bold mb-4">Add to Watchlist</h2>
            <form onSubmit={handleAddStock} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">Ticker</label>
                <input
                  type="text"
                  value={newStock.ticker}
                  onChange={(e) => setNewStock({...newStock, ticker: e.target.value})}
                  className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
                  placeholder="AAPL"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">Company Name</label>
                <input
                  type="text"
                  value={newStock.company_name}
                  onChange={(e) => setNewStock({...newStock, company_name: e.target.value})}
                  className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
                  placeholder="Apple Inc."
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">Sector (Optional)</label>
                <input
                  type="text"
                  value={newStock.sector}
                  onChange={(e) => setNewStock({...newStock, sector: e.target.value})}
                  className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
                  placeholder="Technology"
                />
              </div>
              <div className="flex gap-4">
                <button
                  type="submit"
                  className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg transition"
                >
                  Add
                </button>
                <button
                  type="button"
                  onClick={() => setShowAddModal(false)}
                  className="flex-1 bg-slate-700 hover:bg-slate-600 text-white py-3 rounded-lg transition"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
