import { useEffect, useState } from 'react';
import { useOutletContext } from 'react-router-dom';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
import { api } from '../api/client';
import Header from '../components/Layout/Header';
import StatsCard from '../components/StatsCard';
import SuccessRing from '../components/SuccessRing';

export default function DashboardPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [overview, setOverview] = useState(null);
  const [chart, setChart] = useState([]);

  useEffect(() => {
    Promise.all([api.get('/dashboard/overview'), api.get('/dashboard/chart/monthly')]).then(([ov, ch]) => {
      setOverview(ov.data);
      setChart(ch.data.data || []);
    });
  }, []);

  const stats = overview?.stats;

  return (
    <div>
      <Header title="داشبورد" user={overview?.user || user} lastUpdate={overview?.lastUpdate} onMenuClick={() => setMobileOpen?.(true)} />

      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4 mb-6">
        <StatsCard title="کل سیگنال‌ها" value={stats?.total || 0} icon="📊" color="blue" />
        <StatsCard title="سود" value={stats?.profit || 0} icon="📈" color="green" />
        <StatsCard title="ضرر" value={stats?.loss || 0} icon="📉" color="red" />
        <div className="card flex items-center justify-between">
          <div>
            <p className="text-gray-400 text-sm mb-1">نرخ موفقیت</p>
            <p className="text-2xl font-bold">{stats?.successRate || 0}%</p>
          </div>
          <SuccessRing rate={stats?.successRate || 0} />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <div className="card">
          <h3 className="font-bold mb-4">امروز</h3>
          <div className="grid grid-cols-3 gap-4 text-center text-sm">
            <div>
              <p className="text-gray-500">کل</p>
              <p className="font-bold text-lg">{overview?.stats?.today?.total?.toLocaleString('fa-IR') || 0}</p>
            </div>
            <div>
              <p className="text-gray-500">سود</p>
              <p className="font-bold text-lg text-emerald-400">{overview?.stats?.today?.profit?.toLocaleString('fa-IR') || 0}</p>
            </div>
            <div>
              <p className="text-gray-500">ضرر</p>
              <p className="font-bold text-lg text-red-400">{overview?.stats?.today?.loss?.toLocaleString('fa-IR') || 0}</p>
            </div>
          </div>
        </div>
        <div className="card">
          <h3 className="font-bold mb-4">هفته جاری</h3>
          <div className="grid grid-cols-3 gap-4 text-center text-sm">
            <div>
              <p className="text-gray-500">کل</p>
              <p className="font-bold text-lg">{overview?.stats?.week?.total?.toLocaleString('fa-IR') || 0}</p>
            </div>
            <div>
              <p className="text-gray-500">سود</p>
              <p className="font-bold text-lg text-emerald-400">{overview?.stats?.week?.profit?.toLocaleString('fa-IR') || 0}</p>
            </div>
            <div>
              <p className="text-gray-500">ضرر</p>
              <p className="font-bold text-lg text-red-400">{overview?.stats?.week?.loss?.toLocaleString('fa-IR') || 0}</p>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <h3 className="font-bold mb-4">روند نرخ موفقیت (ماهانه)</h3>
        <div className="h-64" dir="ltr">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={chart}>
              <CartesianGrid stroke="#1c2744" strokeDasharray="3 3" />
              <XAxis dataKey="label" stroke="#6b7280" fontSize={12} />
              <YAxis domain={[50, 100]} stroke="#6b7280" fontSize={12} />
              <Tooltip contentStyle={{ background: '#151d35', border: '1px solid #1c2744', borderRadius: 12 }} />
              <Line type="monotone" dataKey="successRate" stroke="#3b82f6" strokeWidth={2} dot={{ fill: '#3b82f6' }} name="نرخ موفقیت %" />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
}
