
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import * as icon from '@mdi/js';
import BaseIcon from './BaseIcon';
import { useAppSelector } from '../stores/hooks';
import dynamic from 'next/dynamic';

const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

export const PremiumOverview = () => {
  const [trades, setTrades] = useState([]);
  const [loading, setLoading] = useState(true);
  const cardsStyle = useAppSelector((state) => state.style.cardsStyle);
  const corners = useAppSelector((state) => state.style.corners);

  useEffect(() => {
    const fetchTrades = async () => {
      try {
        const response = await axios.get('/trades');
        setTrades(response.data.rows || []);
      } catch (error) {
        console.error('Error fetching trades:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchTrades();
  }, []);

  const stats = React.useMemo(() => {
    if (!trades.length) return { pnl: 0, winRate: 0, profitFactor: 0, avgRR: 0, equity: [] };

    let totalPnL = 0;
    let wins = 0;
    let grossProfit = 0;
    let grossLoss = 0;
    let totalRR = 0;
    const equityData = [];
    let runningPnL = 0;

    trades.forEach((trade) => {
      const pnl = parseFloat(trade.pnl_amount) || 0;
      totalPnL += pnl;
      runningPnL += pnl;
      equityData.push(runningPnL);

      if (trade.is_win) {
        wins++;
        grossProfit += pnl;
      } else {
        grossLoss += Math.abs(pnl);
      }
      totalRR += parseFloat(trade.rr_ratio) || 0;
    });

    return {
      pnl: totalPnL,
      winRate: (wins / trades.length) * 100,
      profitFactor: grossLoss === 0 ? grossProfit : grossProfit / grossLoss,
      avgRR: totalRR / trades.length,
      equity: equityData,
    };
  }, [trades]);

  const chartOptions: any = {
    chart: {
      type: 'area',
      height: 350,
      toolbar: { show: false },
      animations: { enabled: true },
      background: 'transparent',
    },
    colors: ['#0ea5e9'],
    fill: {
      type: 'gradient',
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.45,
        opacityTo: 0.05,
        stops: [20, 100, 100, 100],
      },
    },
    dataLabels: { enabled: false },
    stroke: { curve: 'smooth', width: 3 },
    grid: { borderColor: 'rgba(255,255,255,0.05)', strokeDashArray: 4 },
    xaxis: {
      labels: { show: false },
      axisBorder: { show: false },
      axisTicks: { show: false },
    },
    yaxis: {
      labels: {
        style: { colors: '#64748b' },
        formatter: (val) => `$${val.toFixed(0)}`,
      },
    },
    tooltip: { theme: 'dark' },
  };

  const series = [{ name: 'Equity', data: stats.equity }];

  if (loading) return <div className="p-6 text-gray-500 animate-pulse">Analyzing performance...</div>;

  return (
    <div className="space-y-6 mb-10">
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        {[
          { label: 'Net P&L', value: `$${stats.pnl.toLocaleString()}`, icon: icon.mdiCurrencyUsd, color: stats.pnl >= 0 ? 'text-green-400' : 'text-red-400' },
          { label: 'Win Rate', value: `${stats.winRate.toFixed(1)}%`, icon: icon.mdiChartPie, color: 'text-[#0ea5e9]' },
          { label: 'Profit Factor', value: stats.profitFactor.toFixed(2), icon: icon.mdiTrendingUp, color: 'text-purple-400' },
          { label: 'Avg RR', value: stats.avgRR.toFixed(2), icon: icon.mdiScaleBalance, color: 'text-yellow-400' },
        ].map((item, i) => (
          <div key={i} className={`${corners} ${cardsStyle} p-6 relative overflow-hidden group`}>
            <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
               <BaseIcon path={item.icon} size={48} />
            </div>
            <div className="text-sm text-gray-400 mb-1 font-medium">{item.label}</div>
            <div className={`text-3xl font-bold tracking-tight ${item.color}`}>{item.value}</div>
          </div>
        ))}
      </div>

      <div className={`${corners} ${cardsStyle} p-6`}>
        <div className="flex justify-between items-center mb-6">
          <h3 className="text-lg font-bold text-white">Equity Curve</h3>
          <div className="flex space-x-2">
             <span className="text-xs bg-[#0ea5e9]/10 text-[#0ea5e9] px-2 py-1 rounded">All Accounts</span>
          </div>
        </div>
        <div className="h-80 w-full">
           <Chart options={chartOptions} series={series} type="area" height="100%" />
        </div>
      </div>
    </div>
  );
};
