import { useState, useEffect } from 'react';
import api from '../services/api';
import toast from 'react-hot-toast';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { formatJalaliDate, formatJalaliDateTime } from '../utils/date';

const tabs = [
  { key: 'project-status', label: 'وضعیت پروژه‌ها' },
  { key: 'delayed-tasks', label: 'تسک‌های عقب‌افتاده' },
  { key: 'team-performance', label: 'عملکرد تیم' },
  { key: 'workload', label: 'بار کاری' },
  { key: 'sprint-progress', label: 'پیشرفت اسپرینت' },
  { key: 'time-estimate', label: 'تخمین زمان' },
  { key: 'recent-activities', label: 'فعالیت‌های اخیر' },
  { key: 'risky-projects', label: 'پروژه‌های پرریسک' },
];

const COLORS = ['#6366f1', '#22c55e', '#f59e0b', '#ef4444', '#3b82f6', '#8b5cf6', '#14b8a6', '#ec4899'];
const priorityLabels = { low: 'کم', medium: 'متوسط', high: 'زیاد', urgent: 'فوری' };
const riskLabels = { low: 'کم', medium: 'متوسط', high: 'زیاد', critical: 'بحرانی' };

export default function Reports() {
  const [activeTab, setActiveTab] = useState('project-status');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    api.get(`/reports/${activeTab}`).then(({ data: res }) => setData(res.data)).catch(() => toast.error('خطا')).finally(() => setLoading(false));
  }, [activeTab]);

  const renderTabContent = () => {
    if (loading) return <div className="skeleton" style={{ height: 400, borderRadius: 'var(--radius)' }} />;
    if (!data) return <div style={{ textAlign: 'center', padding: '3rem', color: 'var(--gray-400)' }}>داده‌ای موجود نیست</div>;

    switch (activeTab) {
      case 'project-status':
        return (
          <div className="grid grid-2">
            <div className="card" style={{ padding: '1.5rem' }}>
              <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>توزیع وضعیت پروژه‌ها</h3>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie data={data} dataKey="count" nameKey="status" cx="50%" cy="50%" outerRadius={100} label>
                    {Array.isArray(data) && data.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Legend />
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="card" style={{ padding: '1.5rem' }}>
              <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>جزئیات</h3>
              {Array.isArray(data) && data.map((item, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '0.625rem 0', borderBottom: '1px solid var(--gray-50)' }}>
                  <span style={{ fontSize: '0.875rem' }}>{item.status || item.label || item.name}</span>
                  <span style={{ fontWeight: 600, color: COLORS[i % COLORS.length] }}>{item.count || item.value}</span>
                </div>
              ))}
            </div>
          </div>
        );

      case 'delayed-tasks':
        return (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div className="table-container">
              <table>
                <thead><tr><th>عنوان</th><th>پروژه</th><th>تخصیص‌یافته</th><th>ددلاین</th><th>روزهای تأخیر</th><th>اولویت</th></tr></thead>
                <tbody>
                  {Array.isArray(data) && data.map((t, i) => (
                    <tr key={t.id || i}>
                      <td style={{ fontWeight: 500 }}>{t.title}</td>
                      <td>{t.project?.title || t.project_name || '—'}</td>
                      <td>{t.assignee?.name || t.assignee_name || '—'}</td>
                      <td style={{ color: 'var(--danger)' }}>{formatJalaliDate(t.due_date)}</td>
                      <td><span className="badge badge-danger">{t.delay_days || t.days_delayed || 0} روز</span></td>
                      <td><span className={`badge ${t.priority === 'urgent' || t.priority === 'high' ? 'badge-danger' : 'badge-warning'}`}>{priorityLabels[t.priority] || t.priority || '—'}</span></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        );

      case 'team-performance':
        return (
          <div className="card" style={{ padding: '1.5rem' }}>
            <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>عملکرد اعضای تیم</h3>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={Array.isArray(data) ? data : []} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" />
                <YAxis type="category" dataKey="name" width={120} />
                <Tooltip />
                <Bar dataKey="completed" fill="#22c55e" name="تکمیل شده" />
                <Bar dataKey="in_progress" fill="#6366f1" name="در حال انجام" />
                <Bar dataKey="delayed" fill="#ef4444" name="عقب افتاده" />
              </BarChart>
            </ResponsiveContainer>
          </div>
        );

      case 'workload':
        return (
          <div className="grid grid-2">
            {Array.isArray(data) && data.map((item, i) => (
              <div key={i} className="card" style={{ padding: '1.25rem' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.75rem' }}>
                  <div>
                    <div className="avatar avatar-sm">{item.name?.[0] || '?'}</div>
                    <div style={{ fontSize: '0.9375rem', fontWeight: 600, marginTop: '0.5rem' }}>{item.name}</div>
                    <div style={{ fontSize: '0.8125rem', color: 'var(--gray-500)' }}>{item.tasks_count || item.total || 0} تسک</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '0.75rem', color: 'var(--gray-400)' }}>بار کاری</div>
                    <div style={{ fontSize: '1.25rem', fontWeight: 700, color: (item.load_percent || item.load || 0) > 80 ? 'var(--danger)' : (item.load_percent || item.load || 0) > 50 ? 'var(--warning)' : 'var(--success)' }}>
                      {item.load_percent || item.load || 0}%
                    </div>
                  </div>
                </div>
                <div className="progress-bar"><div className="progress-fill" style={{ width: `${item.load_percent || item.load || 0}%`, background: (item.load_percent || item.load || 0) > 80 ? 'var(--danger)' : (item.load_percent || item.load || 0) > 50 ? 'var(--warning)' : 'var(--success)' }} /></div>
              </div>
            ))}
          </div>
        );

      case 'sprint-progress':
        return (
          <div className="card" style={{ padding: '1.5rem' }}>
            <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>پیشرفت اسپرینت‌ها</h3>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={Array.isArray(data) ? data : []}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="title" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="progress" fill="#6366f1" name="درصد پیشرفت" />
              </BarChart>
            </ResponsiveContainer>
          </div>
        );

      case 'time-estimate':
        return (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div className="table-container">
              <table>
                <thead><tr><th>عنوان</th><th>پروژه</th><th>زمان تخمینی</th><th>زمان واقعی</th><th>تفاوت</th></tr></thead>
                <tbody>
                  {Array.isArray(data) && data.map((t, i) => (
                    <tr key={t.id || i}>
                      <td style={{ fontWeight: 500 }}>{t.title}</td>
                      <td>{t.project?.title || '—'}</td>
                      <td>{t.estimated_time || t.estimated || '—'} ساعت</td>
                      <td>{t.actual_time || t.actual || '—'} ساعت</td>
                      <td>
                        <span className={`badge ${(t.diff || t.difference || 0) > 0 ? 'badge-danger' : 'badge-success'}`}>
                          {t.diff || t.difference || 0} ساعت
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        );

      case 'recent-activities':
        return (
          <div className="card" style={{ padding: '1.5rem' }}>
            {Array.isArray(data) && data.map((a, i) => (
              <div key={i} style={{ display: 'flex', gap: '0.75rem', padding: '0.625rem 0', borderBottom: '1px solid var(--gray-50)' }}>
                <div className="avatar avatar-sm" style={{ width: 32, height: 32, fontSize: '0.75rem' }}>{a.user?.[0] || a.user_name?.[0] || '?'}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '0.875rem' }}>{a.description}</div>
                  <div style={{ fontSize: '0.75rem', color: 'var(--gray-400)', marginTop: '0.25rem' }}>{a.user_name && <strong>{a.user_name}</strong>} {formatJalaliDateTime(a.created_at, a.time_ago || '')}</div>
                </div>
              </div>
            ))}
          </div>
        );

      case 'risky-projects':
        return (
          <div className="grid grid-3">
            {Array.isArray(data) && data.map((p, i) => (
              <div key={p.id || i} className="card" style={{ padding: '1.25rem', borderRight: `4px solid ${p.risk_level === 'high' ? 'var(--danger)' : p.risk_level === 'medium' ? 'var(--warning)' : 'var(--gray-400)'}` }}>
                <h4 style={{ fontSize: '0.9375rem', fontWeight: 600, marginBottom: '0.5rem' }}>{p.title}</h4>
                <div style={{ display: 'grid', gap: '0.375rem', fontSize: '0.8125rem', color: 'var(--gray-600)' }}>
                  <div><strong>ریسک:</strong> <span className={`badge ${p.risk_level === 'high' || p.risk_level === 'critical' ? 'badge-danger' : 'badge-warning'}`}>{riskLabels[p.risk_level] || p.risk_level}</span></div>
                  <div><strong>تسک‌های عقب‌افتاده:</strong> <span style={{ color: 'var(--danger)' }}>{p.delayed_tasks || 0}</span></div>
                  <div><strong>پیشرفت:</strong> {p.progress || 0}%</div>
                </div>
                <div className="progress-bar" style={{ marginTop: '0.75rem' }}><div className="progress-fill" style={{ width: `${p.progress || 0}%`, background: p.risk_level === 'high' ? 'var(--danger)' : 'var(--warning)' }} /></div>
              </div>
            ))}
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="page-container">
      <div className="page-header">
      </div>
      <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginBottom: '1.5rem' }}>
        {tabs.map(tab => (
          <button key={tab.key} className={`btn btn-sm ${activeTab === tab.key ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setActiveTab(tab.key)}>{tab.label}</button>
        ))}
      </div>
      {renderTabContent()}
    </div>
  );
}
