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

const periodMap = { all: 'all', '30days': '30days', '7days': '7days', today: 'today' };
const filters = [
  { id: 'all', label: 'همه' },
  { id: '30days', label: '۳۰ روز' },
  { id: '7days', label: '۷ روز' },
  { id: 'today', label: 'امروز' },
];

export default function StatsPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [period, setPeriod] = useState('all');
  const [stats, setStats] = useState(null);
  const [monthly, setMonthly] = useState([]);
  const [distribution, setDistribution] = useState(null);
  const [weekdays, setWeekdays] = useState([]);

  useEffect(() => {
    const p = periodMap[period];
    Promise.all([
      api.get('/dashboard/stats', { params: { period: p } }),
      api.get('/dashboard/chart/monthly'),
      api.get('/dashboard/chart/distribution', { params: { period: p } }),
      api.get('/dashboard/chart/weekdays'),
    ]).then(([s, m, d, w]) => {
      setStats(s.data);
      setMonthly(m.data.data || []);
      setDistribution(d.data);
      setWeekdays(w.data.data || []);
    });
  }, [period]);

  const pieData = distribution
    ? [
        { name: 'سود', value: distribution.profit, color: '#10b981' },
        { name: 'ضرر', value: distribution.loss, color: '#ef4444' },
      ]
    : [];

  return (
    <div>
      <Header title="آمار و عملکرد" user={user} onMenuClick={() => setMobileOpen?.(true)} />

      <div className="flex flex-wrap gap-2 mb-6">
        {filters.map((f) => (
          <button
            key={f.id}
            onClick={() => setPeriod(f.id)}
            className={`px-4 py-2 rounded-xl text-sm ${period === f.id ? 'bg-accent text-white' : 'btn-outline'}`}
          >
            {f.label}
          </button>
        ))}
      </div>

      <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="📊" />
        <StatsCard title="سود" value={stats?.profit || 0} color="green" />
        <StatsCard title="ضرر" value={stats?.loss || 0} color="red" />
        <div className="card flex items-center justify-between">
          <div>
            <p className="text-gray-400 text-sm">نرخ موفقیت</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 lg:grid-cols-2 gap-6 mb-6">
        <div className="card">
          <h3 className="font-bold mb-4">روند ماهانه</h3>
          <div className="h-56" dir="ltr">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={monthly}>
                <XAxis dataKey="label" stroke="#6b7280" fontSize={11} />
                <YAxis domain={[50, 100]} stroke="#6b7280" fontSize={11} />
                <Tooltip contentStyle={{ background: '#151d35', border: 'none', borderRadius: 8 }} />
                <Line type="monotone" dataKey="successRate" stroke="#3b82f6" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
        <div className="card">
          <h3 className="font-bold mb-4">توزیع سود و ضرر</h3>
          <div className="h-56 flex items-center justify-center" dir="ltr">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} dataKey="value" label={({ name, percent }) => `${name} ${(percent * 100).toFixed(1)}%`}>
                  {pieData.map((entry, i) => (
                    <Cell key={i} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <p className="text-center text-sm text-gray-500 mt-2">
            سود {distribution?.profitPercent}% — ضرر {distribution?.lossPercent}%
          </p>
        </div>
      </div>

      <div className="card">
        <h3 className="font-bold mb-4">بهترین روزهای هفته</h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3">
          {weekdays.map((d) => (
            <div key={d.day} className="bg-navy-900 rounded-xl p-4 text-center">
              <p className="text-gray-500 text-xs mb-1">{d.day}</p>
              <p className="text-xl font-bold text-accent">{d.successRate}%</p>
              <p className="text-xs text-gray-600 mt-1">
                {d.profit}/{d.profit + d.loss}
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
