import { useEffect, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { api } from '../api/client';
import Header from '../components/Layout/Header';
import StatsCard from '../components/StatsCard';
import { formatDateTime } from '../utils/date';

const periods = [
  { id: 'today', label: 'امروز' },
  { id: 'week', label: 'این هفته' },
  { id: 'month', label: 'این ماه' },
  { id: 'all', label: 'همه' },
];

export default function HistoryPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [period, setPeriod] = useState('week');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [data, setData] = useState({ signals: [], totalPages: 1, total: 0 });
  const [stats, setStats] = useState(null);

  useEffect(() => {
    api.get('/dashboard/stats', { params: { period: period === 'all' ? 'all' : period } }).then(({ data }) => setStats(data));
  }, [period]);

  useEffect(() => {
    const t = setTimeout(() => {
      api.get('/signals/history', { params: { period, search, page, limit: 15 } }).then(({ data }) => setData(data));
    }, 300);
    return () => clearTimeout(t);
  }, [period, search, page]);

  return (
    <div>
      <Header title="تاریخچه سیگنال‌ها" user={user} onMenuClick={() => setMobileOpen?.(true)} />

      <div className="flex flex-wrap gap-2 mb-4">
        {periods.map((p) => (
          <button
            key={p.id}
            onClick={() => { setPeriod(p.id); setPage(1); }}
            className={`px-4 py-2 rounded-xl text-sm ${period === p.id ? 'bg-accent text-white' : 'btn-outline'}`}
          >
            {p.label}
          </button>
        ))}
        <input
          className="input-field max-w-xs mr-auto"
          placeholder="جستجوی جفت ارز..."
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
        />
      </div>

      {stats && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
          <StatsCard title="کل" value={stats.total} color="blue" />
          <StatsCard title="سود" value={stats.profit} color="green" />
          <StatsCard title="ضرر" value={stats.loss} color="red" />
          <StatsCard title="نرخ موفقیت" value={`${stats.successRate}%`} color="amber" />
        </div>
      )}

      <div className="card overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="text-gray-500 border-b border-navy-700">
              <th className="py-3 text-right">#</th>
              <th className="py-3 text-right">جفت ارز</th>
              <th className="py-3 text-right">نوع</th>
              <th className="py-3 text-right">زمان ارسال</th>
              <th className="py-3 text-right">زمان بسته شدن</th>
              <th className="py-3 text-right">نتیجه</th>
            </tr>
          </thead>
          <tbody>
            {data.signals.map((s, i) => (
              <tr key={s.id} className="border-b border-navy-700/50 hover:bg-navy-700/30">
                <td className="py-3">{((page - 1) * 15 + i + 1).toLocaleString('fa-IR')}</td>
                <td className="py-3">
                  <Link to={`/signals/${s.id}`} className="text-accent hover:underline font-medium">
                    {s.pair}
                  </Link>
                </td>
                <td className="py-3">
                  <span className={s.type === 'BUY' ? 'badge-buy' : 'badge-sell'}>{s.type}</span>
                </td>
                <td className="py-3">{formatDateTime(s.sentAt)}</td>
                <td className="py-3">{formatDateTime(s.closedAt)}</td>
                <td className="py-3">
                  <span className={s.result === 'profit' ? 'text-emerald-400' : 'text-red-400'}>
                    {s.result === 'profit' ? '● سود' : '● ضرر'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex justify-center gap-2 mt-6">
        <button disabled={page <= 1} onClick={() => setPage((p) => p - 1)} className="btn-outline disabled:opacity-40">
          قبلی
        </button>
        <span className="px-4 py-2 text-gray-400">
          صفحه {page.toLocaleString('fa-IR')} از {data.totalPages.toLocaleString('fa-IR')}
        </span>
        <button disabled={page >= data.totalPages} onClick={() => setPage((p) => p + 1)} className="btn-outline disabled:opacity-40">
          بعدی
        </button>
      </div>
    </div>
  );
}
