'use client';
import { useState } from 'react';
import { initialPrograms } from './trainingData';
const budgetData = [
  { dept: 'Monitoring & Evaluation', planned: 120000, actual: 86500 },
  { dept: 'ICT', planned: 180000, actual: 102000 },
  { dept: 'Procurement', planned: 95000, actual: 68000 },
  { dept: 'Corporate Communication', planned: 75000, actual: 47000 },
  { dept: 'Transport', planned: 45000, actual: 28000 },
  { dept: 'Administration', planned: 60000, actual: 41000 },
];
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend, Cell } from 'recharts';

const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

type CalEvent = { id: string; title: string; start: string; end: string; mode: string; dept: string; color: string };

const MODE_COLORS: Record<string, string> = {
  'In-Person': '#b22698',
  'Online': '#3b82f6',
  'Hybrid': '#f59e0b',
};

export default function TrainingPlanTab() {
  const [activeMonth, setActiveMonth] = useState(3);
  const [activeView, setActiveView] = useState<'calendar' | 'budget'>('calendar');

  const events: CalEvent[] = initialPrograms.map(p => ({
    id: p.id,
    title: p.title,
    start: p.start,
    end: p.end,
    mode: p.mode,
    dept: p.dept,
    color: MODE_COLORS[p.mode] || '#b22698',
  }));

  const monthStr = `2026-${String(activeMonth + 1).padStart(2, '0')}`;
  const monthEvents = events.filter(e => e.start.startsWith(monthStr) || e.end.startsWith(monthStr));

  const budgetChartData = budgetData.map(b => ({
    dept: b.dept.replace(' & ', '/').replace('Corporate Communication', 'Corp. Comm'),
    Planned: Math.round(b.planned / 1000),
    Actual: Math.round(b.actual / 1000),
    Variance: Math.round((b.planned - b.actual) / 1000),
  }));

  const totalPlanned = budgetData.reduce((s, b) => s + b.planned, 0);
  const totalActual = budgetData.reduce((s, b) => s + b.actual, 0);
  const utilization = Math.round((totalActual / totalPlanned) * 100);

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Total Budget (2026)', value: `KES ${(totalPlanned / 1000).toFixed(0)}K`, icon: 'ri-wallet-3-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Spent to Date', value: `KES ${(totalActual / 1000).toFixed(0)}K`, icon: 'ri-coins-line', color: 'text-purple-600 bg-purple-50' },
          { label: 'Budget Utilization', value: `${utilization}%`, icon: 'ri-pie-chart-2-line', color: 'text-orange-600 bg-orange-50' },
          { label: 'Scheduled Events', value: String(events.length), icon: 'ri-calendar-event-line', color: 'text-green-600 bg-green-50' },
        ].map(({ label, value, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></i>
            </div>
            <p className="text-xl font-bold text-gray-800">{value}</p>
            <p className="text-sm text-gray-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
          <div className="flex gap-1 bg-gray-100 rounded-xl p-1">
            {(['calendar', 'budget'] as const).map(v => (
              <button key={v} onClick={() => setActiveView(v)}
                className={`px-4 py-1.5 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${activeView === v ? 'bg-white shadow text-gray-800' : 'text-gray-500'}`}>
                {v === 'calendar' ? 'Training Calendar' : 'Budget Tracking'}
              </button>
            ))}
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              {Object.entries(MODE_COLORS).map(([k, c]) => (
                <div key={k} className="flex items-center gap-1">
                  <div className="w-3 h-3 rounded-full" style={{ background: c }}></div>
                  <span className="text-xs text-gray-500">{k}</span>
                </div>
              ))}
            </div>
            <button className="flex items-center gap-2 px-3 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-600 cursor-pointer hover:bg-gray-50 whitespace-nowrap">
              <i className="ri-file-pdf-line"></i> Export Plan
            </button>
          </div>
        </div>

        {activeView === 'calendar' && (
          <div className="p-5">
            <div className="flex gap-1 mb-5 overflow-x-auto pb-1">
              {MONTHS.map((m, i) => (
                <button key={m} onClick={() => setActiveMonth(i)}
                  className="px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap transition-all flex-shrink-0"
                  style={activeMonth === i ? { background: '#b22698', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                  {m} {events.filter(e => e.start.startsWith(`2026-${String(i + 1).padStart(2, '0')}`)).length > 0 && (
                    <span className={`ml-1 text-xs ${activeMonth === i ? 'text-pink-200' : 'text-pink-500'}`}>
                      ({events.filter(e => e.start.startsWith(`2026-${String(i + 1).padStart(2, '0')}`)).length})
                    </span>
                  )}
                </button>
              ))}
            </div>

            {monthEvents.length === 0 ? (
              <div className="text-center py-12 text-gray-400">
                <div className="w-12 h-12 flex items-center justify-center mx-auto mb-3">
                  <i className="ri-calendar-line text-4xl"></i>
                </div>
                <p className="text-sm">No training events scheduled for {MONTHS[activeMonth]} 2026</p>
              </div>
            ) : (
              <div className="space-y-3">
                {monthEvents.map(e => (
                  <div key={e.id} className="flex items-center gap-4 p-4 border border-gray-100 rounded-xl hover:shadow-sm transition-shadow">
                    <div className="w-1 self-stretch rounded-full" style={{ background: e.color }}></div>
                    <div className="flex-1">
                      <p className="text-sm font-bold text-gray-800">{e.title}</p>
                      <p className="text-xs text-gray-400 mt-0.5">{e.dept}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-medium text-gray-700">{e.start} → {e.end}</p>
                      <span className="text-xs px-2 py-0.5 rounded-full font-medium mt-1 inline-block text-white" style={{ background: e.color }}>{e.mode}</span>
                    </div>
                    <button className="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 cursor-pointer hover:bg-gray-50" title="Export iCal">
                      <i className="ri-calendar-2-line text-gray-500 text-sm"></i>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {activeView === 'budget' && (
          <div className="p-5">
            <div className="mb-5">
              <div className="flex items-center justify-between mb-3">
                <h4 className="font-semibold text-gray-800">Budget vs Actual by Department (KES '000)</h4>
                <div className="flex items-center gap-3 text-xs text-gray-500">
                  <div className="flex items-center gap-1"><div className="w-3 h-3 rounded" style={{ background: '#b22698' }}></div>Planned</div>
                  <div className="flex items-center gap-1"><div className="w-3 h-3 rounded bg-blue-400"></div>Actual</div>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={budgetChartData} barCategoryGap="30%" barGap={4}>
                  <XAxis dataKey="dept" tick={{ fontSize: 11 }} />
                  <YAxis tick={{ fontSize: 11 }} />
                  <Tooltip formatter={(v: number) => `KES ${v}K`} />
                  <Bar dataKey="Planned" fill="#b22698" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="Actual" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    {['Department','Planned Budget','Actual Spend','Variance','Utilization'].map(h => (
                      <th key={h} className="text-left text-xs font-semibold text-gray-500 px-4 py-3 whitespace-nowrap">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {budgetData.map(b => {
                    const variance = b.planned - b.actual;
                    const util = Math.round((b.actual / b.planned) * 100);
                    return (
                      <tr key={b.dept} className="border-b border-gray-50 hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm font-medium text-gray-800">{b.dept}</td>
                        <td className="px-4 py-3 text-sm text-gray-700">KES {b.planned.toLocaleString()}</td>
                        <td className="px-4 py-3 text-sm font-semibold" style={{ color: '#b22698' }}>KES {b.actual.toLocaleString()}</td>
                        <td className="px-4 py-3">
                          <span className="text-sm font-medium text-green-600">KES {variance.toLocaleString()} saved</span>
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <div className="flex-1 bg-gray-100 rounded-full h-2 min-w-[80px]">
                              <div className="h-2 rounded-full" style={{ width: `${util}%`, background: util > 80 ? '#ef4444' : '#b22698' }}></div>
                            </div>
                            <span className="text-xs font-semibold text-gray-600">{util}%</span>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                  <tr className="bg-gray-50 font-semibold">
                    <td className="px-4 py-3 text-sm text-gray-800">TOTAL</td>
                    <td className="px-4 py-3 text-sm text-gray-800">KES {totalPlanned.toLocaleString()}</td>
                    <td className="px-4 py-3 text-sm" style={{ color: '#b22698' }}>KES {totalActual.toLocaleString()}</td>
                    <td className="px-4 py-3 text-sm text-green-600">KES {(totalPlanned - totalActual).toLocaleString()} saved</td>
                    <td className="px-4 py-3 text-sm text-gray-800">{utilization}%</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
