'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { format } from 'date-fns';

export default function FilingsPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [filings, setFilings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTicker, setSearchTicker] = useState('');

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
      return;
    }

    if (session?.user) {
      fetchFilings();
    }
  }, [session, status, router]);

  const fetchFilings = async (ticker?: string) => {
    setLoading(true);
    try {
      const url = ticker
        ? `${process.env.NEXT_PUBLIC_API_URL}/api/filings/${ticker}`
        : `${process.env.NEXT_PUBLIC_API_URL}/api/filings`;

      const response = await fetch(url);
      const data = await response.json();
      setFilings(data);
    } catch (error) {
      console.error('Error fetching filings:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchFilings(searchTicker || undefined);
  };

  const handleRefresh = async (ticker: string) => {
    try {
      await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/filings/refresh/${ticker}`, {
        method: 'POST'
      });
      fetchFilings(ticker);
    } catch (error) {
      console.error('Error refreshing filings:', error);
    }
  };

  const getFilingTypeColor = (type: string) => {
    switch (type) {
      case '10-K': return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
      case '10-Q': return 'bg-green-500/20 text-green-400 border-green-500/30';
      case '8-K': return 'bg-purple-500/20 text-purple-400 border-purple-500/30';
      default: return 'bg-slate-500/20 text-slate-400 border-slate-500/30';
    }
  };

  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">SEC Filings</h1>
          <Link
            href="/watchlist/add"
            className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
          >
            + Add to Watchlist
          </Link>
        </div>

        <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700 mb-8">
          <form onSubmit={handleSearch} className="flex gap-4">
            <input
              type="text"
              value={searchTicker}
              onChange={(e) => setSearchTicker(e.target.value)}
              className="flex-1 bg-slate-700/50 border border-slate-600 rounded-lg px-4 py-3 text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Search by ticker (e.g., AAPL)"
            />
            <button
              type="submit"
              className="bg-blue-600 hover:bg-blue-700 px-6 py-3 rounded-lg transition"
            >
              Search
            </button>
            <button
              type="button"
              onClick={() => { setSearchTicker(''); fetchFilings(); }}
              className="bg-slate-700 hover:bg-slate-600 px-6 py-3 rounded-lg transition"
            >
              Clear
            </button>
          </form>
        </div>

        <div className="bg-slate-800/50 rounded-lg border border-slate-700 overflow-hidden">
          {filings.length > 0 ? (
            <table className="w-full">
              <thead className="bg-slate-700/50">
                <tr>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Ticker</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Company</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Type</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Filing Date</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filings.map((filing: any) => (
                  <tr key={filing.id} className="border-t border-slate-700 hover:bg-slate-700/30 transition">
                    <td className="px-6 py-4 font-semibold">{filing.ticker}</td>
                    <td className="px-6 py-4">{filing.company_name}</td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getFilingTypeColor(filing.filing_type)}`}>
                        {filing.filing_type}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      {format(new Date(filing.filing_date), 'MMM dd, yyyy')}
                    </td>
                    <td className="px-6 py-4">
                      <button
                        onClick={() => window.open(`https://www.sec.gov/Archives/${filing.accession_number.replace(/-/g, '')}/${filing.accession_number}-index.htm`, '_blank')}
                        className="text-blue-400 hover:text-blue-300 transition mr-4"
                      >
                        View on SEC
                      </button>
                      <button
                        onClick={() => handleRefresh(filing.ticker)}
                        className="text-green-400 hover:text-green-300 transition"
                      >
                        Refresh
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="text-center py-12">
              <p className="text-slate-400 text-lg mb-4">No filings found</p>
              <p className="text-slate-500 text-sm">
                Add stocks to your watchlist to track their SEC filings
              </p>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
