'use client';
import { useState } from 'react';
import HRLayout from '../../../components/HRLayout';
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Legend
} from 'recharts';
import { useNotifications, NotifType } from '../../../lib/notificationsContext';

const PRIMARY = '#B22698';
const YELLOW = '#FFC107';

const headcountTrend = [
  { month: 'Oct', active: 1198 }, { month: 'Nov', active: 1210 },
  { month: 'Dec', active: 1205 }, { month: 'Jan', active: 1220 },
  { month: 'Feb', active: 1235 }, { month: 'Mar', active: 1248 },
];

const terminationByCategory = [
  { category: 'Voluntary', count: 18 },
  { category: 'Involuntary', count: 9 },
  { category: 'Other', count: 4 },
];

const trainingHoursByDept = [
  { dept: 'Finance', hours: 320 },
  { dept: 'ICT', hours: 480 },
  { dept: 'Operations', hours: 260 },
  { dept: 'HR', hours: 190 },
  { dept: 'Procurement', hours: 210 },
  { dept: 'M&E', hours: 340 },
];

const disciplinaryBySeverity = [
  { name: 'High', value: 4, color: '#C62828' },
  { name: 'Medium', value: 3, color: '#E65100' },
  { name: 'Low', value: 3, color: '#2E7D32' },
];

const turnoverTrend = [
  { month: 'Oct', rate: 1.2 }, { month: 'Nov', rate: 1.8 },
  { month: 'Dec', rate: 2.1 }, { month: 'Jan', rate: 1.5 },
  { month: 'Feb', rate: 1.9 }, { month: 'Mar', rate: 1.3 },
];

const kpiCards = [
  { label: 'Total Headcount', value: '1,248', icon: 'ri-team-line', color: PRIMARY, sub: '+13 this month' },
  { label: 'Turnover Rate', value: '1.6%', icon: 'ri-user-unfollow-line', color: '#ef4444', sub: 'Last 6 months avg' },
  { label: 'Training Completion', value: '78%', icon: 'ri-graduation-cap-line', color: '#3B82F6', sub: 'Target: 85%' },
  { label: 'Open Disciplinary Cases', value: '10', icon: 'ri-scales-3-line', color: YELLOW, sub: '4 High severity' },
];

const alertStyle: Record<string, { border: string; icon: string; iconColor: string; bg: string; badgeBg: string }> = {
  warning: { border: 'border-l-yellow-400', icon: 'ri-alert-line', iconColor: 'text-yellow-600', bg: 'bg-yellow-50', badgeBg: 'bg-yellow-100 text-yellow-700' },
  error: { border: 'border-l-red-500', icon: 'ri-error-warning-line', iconColor: 'text-red-600', bg: 'bg-red-50', badgeBg: 'bg-red-100 text-red-700' },
  info: { border: 'border-l-blue-400', icon: 'ri-information-line', iconColor: 'text-blue-600', bg: 'bg-blue-50', badgeBg: 'bg-blue-100 text-blue-700' },
  success: { border: 'border-l-green-500', icon: 'ri-checkbox-circle-line', iconColor: 'text-green-600', bg: 'bg-green-50', badgeBg: 'bg-green-100 text-green-700' },
};

const notifTypeLabel: Record<NotifType, string> = {
  leave: 'Leave', appraisal: 'Appraisal', payroll: 'Payroll',
  training: 'Training', employee: 'Employee', system: 'System',
};

const notifTypeIcon: Record<NotifType, string> = {
  leave: 'ri-calendar-check-line', appraisal: 'ri-bar-chart-line',
  payroll: 'ri-money-dollar-circle-line', training: 'ri-graduation-cap-line',
  employee: 'ri-team-line', system: 'ri-settings-3-line',
};

function timeAgo(ts: string) {
  const diff = Date.now() - new Date(ts).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  return days === 1 ? '1 day ago' : `${days} days ago`;
}

const ALL_TYPES: Array<'All' | NotifType> = ['All', 'leave', 'appraisal', 'payroll', 'training', 'employee', 'system'];

const REPORT_TYPES = [
  { label: 'Headcount Report', icon: 'ri-team-line', desc: 'Active employees by dept, position, gender' },
  { label: 'Turnover Report', icon: 'ri-user-unfollow-line', desc: 'Terminations by category, reason, period' },
  { label: 'Training Summary', icon: 'ri-graduation-cap-line', desc: 'Hours, cost, completion rate by dept' },
  { label: 'Disciplinary Summary', icon: 'ri-scales-3-line', desc: 'Cases by severity, type, department' },
  { label: 'Leave Liability', icon: 'ri-calendar-check-line', desc: 'Accrued leave balances and liability cost' },
];

export default function AnalyticsPage() {
  const { notifications, dismiss, dismissAll, markRead, markAllRead } = useNotifications();
  const [typeFilter, setTypeFilter] = useState<'All' | NotifType>('All');
  const [exportFormat, setExportFormat] = useState<'excel' | 'pdf'>('excel');

  const filtered = typeFilter === 'All' ? notifications : notifications.filter(n => n.type === typeFilter);
  const unread = notifications.filter(n => !n.read).length;

  const handleExport = (reportLabel: string) => {
    if (exportFormat === 'excel') {
      const csvData = [
        ['Uwezo Fund HRMS - ' + reportLabel],
        ['Generated:', new Date().toLocaleDateString('en-KE')],
        [],
        ['Department', 'Headcount', 'Turnover Rate', 'Training Hours', 'Leave Days'],
        ['ICT', '45', '1.2%', '480', '120'],
        ['Monitoring & Evaluation', '38', '0.8%', '340', '95'],
        ['Finance', '22', '1.5%', '210', '65'],
        ['Procurement', '18', '2.1%', '190', '48'],
        ['Transport', '15', '0.5%', '120', '38'],
        ['Corporate Communication', '12', '1.8%', '160', '32'],
        [],
        ['Total', '150', '1.3%', '1500', '398'],
      ];
      const csv = csvData.map(row => row.join(',')).join('\n');
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportLabel.replace(/\s+/g, '-')}-${new Date().toISOString().split('T')[0]}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } else {
      if (typeof window !== 'undefined') window.print();
    }
  };

  return (
    <HRLayout title="Analytics & Alerts" breadcrumb="HR">
      <div className="grid grid-cols-4 gap-4 mb-6">
        {kpiCards.map(k => (
          <div key={k.label} className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: k.color + '18' }}>
                <i className={`${k.icon} text-xl`} style={{ color: k.color }}></i>
              </div>
            </div>
            <p className="text-3xl font-bold text-gray-800">{k.value}</p>
            <p className="text-sm font-medium text-gray-600 mt-1">{k.label}</p>
            <p className="text-xs text-gray-400 mt-0.5">{k.sub}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-3 gap-5 mb-6">
        <div className="col-span-2 bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <h3 className="font-semibold text-gray-800 text-sm mb-4">Headcount Trend (Active Employees)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={headcountTrend}>
              <defs>
                <linearGradient id="hcGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={PRIMARY} stopOpacity={0.3} />
                  <stop offset="95%" stopColor={PRIMARY} stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="month" tick={{ fontSize: 12 }} />
              <YAxis domain={[1180, 1260]} tick={{ fontSize: 12 }} />
              <Tooltip />
              <Area type="monotone" dataKey="active" stroke={PRIMARY} fill="url(#hcGrad)" name="Active Employees" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <h3 className="font-semibold text-gray-800 text-sm mb-4">Disciplinary Cases by Severity</h3>
          <ResponsiveContainer width="100%" height={140}>
            <PieChart>
              <Pie data={disciplinaryBySeverity} cx="50%" cy="50%" innerRadius={40} outerRadius={65} dataKey="value">
                {disciplinaryBySeverity.map((entry, i) => <Cell key={i} fill={entry.color} />)}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
          <div className="space-y-1.5 mt-2">
            {disciplinaryBySeverity.map(d => (
              <div key={d.name} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ background: d.color }}></div>
                  <span className="text-xs text-gray-600">{d.name} Severity</span>
                </div>
                <span className="text-xs font-semibold text-gray-700">{d.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-5 mb-6">
        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <h3 className="font-semibold text-gray-800 text-sm mb-4">Termination by Category</h3>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={terminationByCategory}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="category" tick={{ fontSize: 12 }} />
              <YAxis tick={{ fontSize: 12 }} />
              <Tooltip />
              <Bar dataKey="count" name="Terminations" radius={[6, 6, 0, 0]}>
                {terminationByCategory.map((entry, i) => (
                  <Cell key={i} fill={i === 0 ? PRIMARY : i === 1 ? '#ef4444' : '#6b7280'} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
        <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
          <h3 className="font-semibold text-gray-800 text-sm mb-4">Training Hours by Department</h3>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={trainingHoursByDept} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis type="number" tick={{ fontSize: 11 }} />
              <YAxis dataKey="dept" type="category" tick={{ fontSize: 11 }} width={70} />
              <Tooltip />
              <Bar dataKey="hours" fill="#3B82F6" name="Hours" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100 mb-6">
        <h3 className="font-semibold text-gray-800 text-sm mb-4">Turnover Rate Trend (%)</h3>
        <ResponsiveContainer width="100%" height={180}>
          <LineChart data={turnoverTrend}>
            <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
            <XAxis dataKey="month" tick={{ fontSize: 12 }} />
            <YAxis domain={[0, 3]} tick={{ fontSize: 12 }} tickFormatter={v => `${v}%`} />
            <Tooltip formatter={(v: any) => [`${v}%`, 'Turnover Rate']} />
            <Line type="monotone" dataKey="rate" stroke="#ef4444" strokeWidth={2.5} dot={{ fill: '#ef4444', r: 4 }} name="Turnover Rate" />
          </LineChart>
        </ResponsiveContainer>
      </div>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 mb-6">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
          <div>
            <h3 className="font-bold text-gray-800">Reports</h3>
            <p className="text-xs text-gray-400 mt-0.5">Export HR reports in Excel or PDF format</p>
          </div>
          <div className="flex items-center gap-2 bg-gray-100 rounded-xl p-1">
            <button onClick={() => setExportFormat('excel')}
              className={`px-4 py-1.5 rounded-lg text-xs font-semibold cursor-pointer whitespace-nowrap transition-all ${exportFormat === 'excel' ? 'bg-white shadow text-gray-800' : 'text-gray-500'}`}>
              Excel
            </button>
            <button onClick={() => setExportFormat('pdf')}
              className={`px-4 py-1.5 rounded-lg text-xs font-semibold cursor-pointer whitespace-nowrap transition-all ${exportFormat === 'pdf' ? 'bg-white shadow text-gray-800' : 'text-gray-500'}`}>
              PDF
            </button>
          </div>
        </div>
        <div className="p-5 grid grid-cols-5 gap-3">
          {REPORT_TYPES.map(r => (
            <div key={r.label} className="border border-gray-100 rounded-xl p-4 hover:shadow-sm transition-shadow">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center mb-3" style={{ background: '#F9E6F5' }}>
                <i className={`${r.icon} text-lg`} style={{ color: PRIMARY }}></i>
              </div>
              <p className="text-sm font-semibold text-gray-800 mb-1">{r.label}</p>
              <p className="text-xs text-gray-400 mb-3">{r.desc}</p>
              <button onClick={() => handleExport(r.label)}
                className="w-full py-1.5 rounded-lg text-xs font-semibold text-white cursor-pointer whitespace-nowrap hover:opacity-90 transition-opacity"
                style={{ background: PRIMARY }}>
                Export {exportFormat.toUpperCase()}
              </button>
            </div>
          ))}
        </div>
      </div>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
        <div className="px-5 py-4 border-b border-gray-100">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <h3 className="font-bold text-gray-800">System Alerts & Notifications</h3>
              {unread > 0 && (
                <span className="text-white text-xs px-2 py-0.5 rounded-full font-semibold" style={{ background: PRIMARY }}>{unread} unread</span>
              )}
            </div>
            <div className="flex gap-2">
              <button onClick={markAllRead} className="text-xs text-gray-500 hover:text-gray-800 cursor-pointer whitespace-nowrap px-3 py-1.5 border border-gray-200 rounded-lg hover:bg-gray-50">Mark all read</button>
              <button onClick={dismissAll} className="text-xs cursor-pointer whitespace-nowrap px-3 py-1.5 rounded-lg text-white" style={{ background: PRIMARY }}>Dismiss All</button>
            </div>
          </div>
          <div className="flex gap-2 flex-wrap">
            {ALL_TYPES.map(t => (
              <button key={t} onClick={() => setTypeFilter(t)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${typeFilter === t ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                style={typeFilter === t ? { background: PRIMARY } : {}}>
                {t !== 'All' && <i className={`${notifTypeIcon[t as NotifType]} text-xs`}></i>}
                {t === 'All' ? 'All' : notifTypeLabel[t as NotifType]}
                {t !== 'All' && (
                  <span className={`text-xs px-1 rounded-full ${typeFilter === t ? 'bg-white/30 text-white' : 'bg-gray-200 text-gray-500'}`}>
                    {notifications.filter(n => n.type === t).length}
                  </span>
                )}
              </button>
            ))}
          </div>
        </div>
        <div className="p-5 space-y-3">
          {filtered.length === 0 && (
            <div className="text-center py-10 text-gray-400">
              <div className="w-12 h-12 flex items-center justify-center mx-auto mb-2"><i className="ri-checkbox-circle-line text-4xl text-green-400"></i></div>
              <p className="text-sm">No notifications in this category.</p>
            </div>
          )}
          {filtered.map(n => {
            const s = alertStyle[n.alertType];
            return (
              <div key={n.id} onClick={() => markRead(n.id)}
                className={`flex items-start gap-3 p-4 rounded-xl border-l-4 cursor-pointer transition-all hover:shadow-sm ${s.border} ${n.read ? 'bg-gray-50/50' : s.bg}`}>
                <div className={`w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${n.read ? 'bg-gray-100' : 'bg-white'}`}>
                  <i className={`${s.icon} ${s.iconColor} text-lg`}></i>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <div className="flex items-center gap-2 flex-wrap">
                        <p className={`text-sm ${n.read ? 'text-gray-600' : 'font-semibold text-gray-800'}`}>{n.title}</p>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${s.badgeBg}`}>{notifTypeLabel[n.type]}</span>
                        {!n.read && <span className="w-2 h-2 rounded-full inline-block" style={{ background: PRIMARY }}></span>}
                      </div>
                      <p className="text-xs text-gray-600 mt-0.5">{n.message}</p>
                      <p className="text-xs text-gray-400 mt-1">{timeAgo(n.timestamp)} · {n.timestamp}</p>
                    </div>
                    <button onClick={e => { e.stopPropagation(); dismiss(n.id); }}
                      className="w-6 h-6 flex items-center justify-center rounded-full hover:bg-white/60 cursor-pointer flex-shrink-0 text-gray-300 hover:text-gray-600">
                      <i className="ri-close-line text-sm"></i>
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </HRLayout>
  );
}
