'use client';

import { useSession } from '@/lib/better-auth';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { format } from 'date-fns';
import Link from 'next/link';

export default function PortfolioPage() {
  const { data: session, isPending } = useSession();
  const router = useRouter();
  const [portfolio, setPortfolio] = useState([]);
  const [summary, setSummary] = useState({ total_value: 0, total_gain_loss: 0, cost_basis: 0 });
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newHolding, setNewHolding] = useState({ ticker: '', shares: '', avg_cost: '' });

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

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

  const fetchPortfolio = async (userId: string) => {
    try {
      const [portfolioRes, summaryRes] = await Promise.all([
        fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${userId}`),
        fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio/${userId}/summary`)
      ]);

      const portfolioData = await portfolioRes.json();
      const summaryData = await summaryRes.json();

      setPortfolio(portfolioData);
      setSummary(summaryData);
    } catch (error) {
      console.error('Error fetching portfolio:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddHolding = async (e: React.FormEvent) => {
    e.preventDefault();
    const userId = session?.user?.id;
    if (!userId) return;

    try {
      await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/portfolio`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: userId,
          ticker: newHolding.ticker.toUpperCase(),
          shares: parseFloat(newHolding.shares),
          avg_cost: parseFloat(newHolding.avg_cost)
        })
      });

      setShowAddModal(false);
      setNewHolding({ ticker: '', shares: '', avg_cost: '' });
      fetchPortfolio(userId);
    } catch (error) {
      console.error('Error adding holding:', error);
    }
  };

  const handleDeleteHolding = async (id: number) => {
    if (!confirm('Are you sure you want to delete this holding?')) return;
    const userId = session?.user?.id;
    if (!userId) return;

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

      fetchPortfolio(userId);
    } catch (error) {
      console.error('Error deleting holding:', 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>;
  }

  const pieData = portfolio.length > 0 ? portfolio.map((p: any) => ({
    name: p.ticker,
    value: p.current_value || (p.shares * p.avg_cost)
  })) : [];

  const COLORS = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#ec4899'];

  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">Portfolio</h1>
          <button
            onClick={() => setShowAddModal(true)}
            className="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
          >
            + Add Holding
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
            <h3 className="text-slate-400 mb-2">Total Value</h3>
            <p className="text-3xl font-bold text-green-400">
              ${summary.total_value?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '$0.00'}
            </p>
          </div>
          <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
            <h3 className="text-slate-400 mb-2">Total Gain/Loss</h3>
            <p className={`text-3xl font-bold ${summary.total_gain_loss >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              {summary.total_gain_loss >= 0 ? '+' : ''}${summary.total_gain_loss?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '$0.00'}
            </p>
          </div>
          <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
            <h3 className="text-slate-400 mb-2">Positions</h3>
            <p className="text-3xl font-bold text-blue-400">{portfolio.length}</p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
          <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
            <h3 className="text-xl font-semibold mb-4">Portfolio Allocation</h3>
            {pieData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={pieData}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    outerRadius={100}
                    label={(entry) => `${entry.name} ($${(entry.value / 1000).toFixed(1)}k)`}
                  >
                    {pieData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-slate-400 text-center py-8">No holdings yet</p>
            )}
          </div>

          <div className="bg-slate-800/50 rounded-lg p-6 border border-slate-700">
            <h3 className="text-xl font-semibold mb-4">Performance</h3>
            {portfolio.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={portfolio.map((p: any) => ({ name: p.ticker, value: p.gain_loss_pct || 0 }))}>
                  <XAxis dataKey="name" stroke="#64748b" />
                  <YAxis stroke="#64748b" />
                  <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                  <Tooltip contentStyle={{ backgroundColor: '#1e293b', border: '#334155', borderRadius: '8px' }} />
                  <Line type="monotone" dataKey="value" stroke="#8b5cf6" strokeWidth={2} dot={{ fill: '#8b5cf6' }} />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-slate-400 text-center py-8">No performance data yet</p>
            )}
          </div>
        </div>

        <div className="bg-slate-800/50 rounded-lg border border-slate-700 overflow-hidden">
          <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">Shares</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Avg Cost</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Current Price</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Value</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Gain/Loss</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">%</th>
                <th className="px-6 py-3 text-left text-sm font-semibold text-slate-300">Actions</th>
              </tr>
            </thead>
            <tbody>
              {portfolio.map((holding: any) => (
                <tr key={holding.id} className="border-t border-slate-700 hover:bg-slate-700/30 transition">
                  <td className="px-6 py-4 font-semibold">{holding.ticker}</td>
                  <td className="px-6 py-4">{holding.shares.toLocaleString()}</td>
                  <td className="px-6 py-4">${holding.avg_cost.toFixed(2)}</td>
                  <td className="px-6 py-4">${holding.current_price?.toFixed(2) || 'N/A'}</td>
                  <td className="px-6 py-4">${holding.current_value?.toFixed(2) || 'N/A'}</td>
                  <td className={`px-6 py-4 ${holding.gain_loss >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {holding.gain_loss >= 0 ? '+' : ''}${holding.gain_loss?.toFixed(2) || '0.00'}
                  </td>
                  <td className={`px-6 py-4 ${holding.gain_loss_pct >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {holding.gain_loss_pct >= 0 ? '+' : ''}{holding.gain_loss_pct?.toFixed(2) || '0.00'}%
                  </td>
                  <td className="px-6 py-4">
                    <button
                      onClick={() => handleDeleteHolding(holding.id)}
                      className="text-red-400 hover:text-red-300 transition"
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </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 Holding</h2>
            <form onSubmit={handleAddHolding} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">Ticker</label>
                <input
                  type="text"
                  value={newHolding.ticker}
                  onChange={(e) => setNewHolding({...newHolding, 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">Shares</label>
                <input
                  type="number"
                  step="0.0001"
                  value={newHolding.shares}
                  onChange={(e) => setNewHolding({...newHolding, shares: e.target.value})}
                  className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
                  placeholder="100"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-2">Average Cost</label>
                <input
                  type="number"
                  step="0.01"
                  value={newHolding.avg_cost}
                  onChange={(e) => setNewHolding({...newHolding, avg_cost: e.target.value})}
                  className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white"
                  placeholder="150.00"
                  required
                />
              </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>
  );
}
