'use client';
import { useState } from 'react';
import SectionHeader from './SectionHeader';
import ToastNotif from './ToastNotif';

interface ReportTemplate {
  id: number;
  name: string;
  category: string;
  fields: string[];
  schedule: string;
  lastRun: string;
  recipients: string;
  active: boolean;
}

const TEMPLATES: ReportTemplate[] = [
  { id: 1, name: 'Employee Master List', category: 'HR', fields: ['Employee ID', 'Full Name', 'Department', 'Grade', 'Category', 'Date Joined', 'Status'], schedule: 'Monthly', lastRun: '2026-04-01', recipients: 'hr@uwezo.go.ke', active: true },
  { id: 2, name: 'Headcount by Department', category: 'HR', fields: ['Department', 'Total Staff', 'Permanent', 'Contract', 'Temporary', 'Intern'], schedule: 'Weekly', lastRun: '2026-04-08', recipients: 'hr@uwezo.go.ke, ceo@uwezo.go.ke', active: true },
  { id: 3, name: 'Monthly Turnover Report', category: 'Analytics', fields: ['Month', 'Resignations', 'Terminations', 'Retirements', 'Turnover Rate'], schedule: 'Monthly', lastRun: '2026-04-01', recipients: 'hr@uwezo.go.ke', active: true },
  { id: 4, name: 'Training Completion Summary', category: 'Training', fields: ['Employee', 'Program', 'Start Date', 'End Date', 'Completion %', 'Certificate'], schedule: 'Quarterly', lastRun: '2026-03-31', recipients: 'training@uwezo.go.ke', active: true },
  { id: 5, name: 'Leave Utilization Report', category: 'Leave', fields: ['Employee', 'Leave Type', 'Days Taken', 'Balance', 'Department'], schedule: 'Monthly', lastRun: '2026-04-01', recipients: 'hr@uwezo.go.ke', active: false },
  { id: 6, name: 'Disciplinary Cases Summary', category: 'Compliance', fields: ['Case No.', 'Employee', 'Offense', 'Severity', 'Status', 'Outcome'], schedule: 'Quarterly', lastRun: '2026-03-31', recipients: 'legal@uwezo.go.ke', active: true },
];

const AVAILABLE_FIELDS = ['Employee ID', 'Full Name', 'Department', 'Grade', 'Category', 'Date Joined', 'Status', 'Salary', 'Leave Balance', 'Training Hours', 'Performance Score', 'Manager', 'Location', 'Gender', 'Nationality', 'Contract End', 'Probation End'];
const SCHEDULE_OPTIONS = ['Daily', 'Weekly', 'Monthly', 'Quarterly', 'Annually', 'On-demand'];

export default function ReportTemplatesSection() {
  const [templates, setTemplates] = useState<ReportTemplate[]>(TEMPLATES);
  const [toast, setToast] = useState('');
  const [activeTab, setActiveTab] = useState<'templates' | 'custom'>('templates');
  const [customFields, setCustomFields] = useState<string[]>([]);
  const [customName, setCustomName] = useState('');
  const [customSchedule, setCustomSchedule] = useState('Monthly');
  const [customRecipients, setCustomRecipients] = useState('');
  const [runningId, setRunningId] = useState<number | null>(null);
  const [scheduleModal, setScheduleModal] = useState<ReportTemplate | null>(null);

  const toggleActive = (id: number) => {
    setTemplates(ts => ts.map(t => t.id === id ? { ...t, active: !t.active } : t));
    setToast('Report schedule updated');
  };

  const runReport = (id: number) => {
    setRunningId(id);
    setTimeout(() => { setRunningId(null); setToast('Report generated and sent successfully'); }, 2000);
  };

  const catColors: Record<string, string> = { HR: 'bg-blue-100 text-blue-700', Analytics: 'bg-purple-100 text-purple-700', Training: 'bg-green-100 text-green-700', Leave: 'bg-amber-100 text-amber-700', Compliance: 'bg-red-100 text-red-600' };

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {scheduleModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-gray-800">Edit Schedule</h3>
              <button onClick={() => setScheduleModal(null)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer"><i className="ri-close-line"></i></button>
            </div>
            <p className="text-xs text-gray-500 mb-4">{scheduleModal.name}</p>
            <div className="space-y-3">
              <div><label className="text-xs font-semibold text-gray-600 block mb-2">Frequency</label>
                <div className="flex flex-wrap gap-2">
                  {SCHEDULE_OPTIONS.map(s => (
                    <button key={s} onClick={() => setTemplates(ts => ts.map(t => t.id === scheduleModal.id ? { ...t, schedule: s } : t))}
                      className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${scheduleModal.schedule === s ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                      style={scheduleModal.schedule === s ? { background: '#b828a0' } : {}}>{s}</button>
                  ))}
                </div>
              </div>
              <div><label className="text-xs font-semibold text-gray-600 block mb-1">Recipient Emails</label>
                <input defaultValue={scheduleModal.recipients} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" placeholder="email1@org.com, email2@org.com" /></div>
            </div>
            <button onClick={() => { setScheduleModal(null); setToast('Schedule saved'); }} className="mt-4 w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Save Schedule</button>
          </div>
        </div>
      )}

      <SectionHeader icon="ri-file-chart-line" title="Report Templates" desc="Pre-defined and custom report templates with automated email delivery" />

      <div className="flex gap-2 mb-4">
        {[{ k: 'templates' as const, l: 'Pre-defined Templates' }, { k: 'custom' as const, l: 'Custom Report Builder' }].map(t => (
          <button key={t.k} onClick={() => setActiveTab(t.k)}
            className={`px-4 py-2 rounded-xl text-xs font-semibold cursor-pointer whitespace-nowrap border transition-all ${activeTab === t.k ? 'text-white border-transparent' : 'bg-white text-gray-600 border-gray-200'}`}
            style={activeTab === t.k ? { background: '#b828a0' } : {}}>{t.l}</button>
        ))}
      </div>

      {activeTab === 'templates' && (
        <div className="space-y-3">
          {templates.map(tmpl => (
            <div key={tmpl.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 hover:-translate-y-0.5 transition-transform">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-pink-50 flex items-center justify-center flex-shrink-0">
                    <i className="ri-file-chart-line text-xl" style={{ color: '#b828a0' }}></i>
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-bold text-gray-800">{tmpl.name}</p>
                      <span className={`text-xs px-2.5 py-0.5 rounded-full font-medium ${catColors[tmpl.category] || 'bg-gray-100 text-gray-600'}`}>{tmpl.category}</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-0.5">{tmpl.schedule} · To: {tmpl.recipients} · Last run: {tmpl.lastRun}</p>
                  </div>
                </div>
                <div className="flex items-center gap-1.5">
                  <button onClick={() => toggleActive(tmpl.id)}
                    className={`relative w-10 h-5 rounded-full transition-all cursor-pointer flex-shrink-0 ${tmpl.active ? '' : 'bg-gray-200'}`}
                    style={tmpl.active ? { background: '#b828a0' } : {}}>
                    <div className="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow-sm transition-all" style={tmpl.active ? { left: '22px' } : { left: '2px' }}></div>
                  </button>
                  <button onClick={() => setScheduleModal(tmpl)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer"><i className="ri-time-line text-blue-400 text-sm"></i></button>
                  <button onClick={() => runReport(tmpl.id)} disabled={runningId === tmpl.id}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border transition-all hover:bg-pink-50" style={{ color: '#b828a0', borderColor: '#b828a0' }}>
                    {runningId === tmpl.id ? <><i className="ri-loader-4-line animate-spin text-xs"></i> Running...</> : <><i className="ri-play-circle-line text-xs"></i> Run Now</>}
                  </button>
                </div>
              </div>
              <div className="mt-3 flex flex-wrap gap-1.5">
                {tmpl.fields.slice(0, 5).map(f => <span key={f} className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-500">{f}</span>)}
                {tmpl.fields.length > 5 && <span className="text-xs px-2 py-0.5 rounded-full bg-pink-100 font-medium" style={{ color: '#b828a0' }}>+{tmpl.fields.length - 5} more</span>}
              </div>
            </div>
          ))}
        </div>
      )}

      {activeTab === 'custom' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
          <p className="text-sm font-bold text-gray-800 mb-4">Build Custom Report</p>
          <div className="grid grid-cols-2 gap-4 mb-5">
            <div className="col-span-2">
              <label className="text-xs font-semibold text-gray-600 block mb-1">Report Name</label>
              <input value={customName} onChange={e => setCustomName(e.target.value)} placeholder="e.g. Quarterly Headcount Analysis" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" />
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-2">Schedule</label>
              <div className="flex flex-wrap gap-1.5">
                {SCHEDULE_OPTIONS.map(s => (
                  <button key={s} onClick={() => setCustomSchedule(s)}
                    className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${customSchedule === s ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                    style={customSchedule === s ? { background: '#b828a0' } : {}}>{s}</button>
                ))}
              </div>
            </div>
            <div>
              <label className="text-xs font-semibold text-gray-600 block mb-1">Recipients (comma separated)</label>
              <input value={customRecipients} onChange={e => setCustomRecipients(e.target.value)} placeholder="email@org.com, ..." className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" />
            </div>
          </div>

          <div className="mb-5">
            <label className="text-xs font-semibold text-gray-600 block mb-2">Select Fields to Include</label>
            <div className="flex flex-wrap gap-2">
              {AVAILABLE_FIELDS.map(f => (
                <button key={f} onClick={() => setCustomFields(fs => fs.includes(f) ? fs.filter(x => x !== f) : [...fs, f])}
                  className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${customFields.includes(f) ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-pink-300'}`}
                  style={customFields.includes(f) ? { background: '#b828a0' } : {}}>
                  {customFields.includes(f) && <i className="ri-check-line mr-1 text-xs"></i>}
                  {f}
                </button>
              ))}
            </div>
            {customFields.length > 0 && (
              <p className="text-xs text-gray-400 mt-2">{customFields.length} fields selected</p>
            )}
          </div>

          <div className="flex gap-3">
            <button onClick={() => setToast('Custom report saved as template')} disabled={!customName || customFields.length === 0}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap disabled:opacity-40"
              style={{ background: '#b828a0' }}>
              <div className="w-4 h-4 flex items-center justify-center"><i className="ri-save-line text-sm"></i></div>
              Save Template
            </button>
            <button onClick={() => setToast('Report generated and downloaded')} disabled={!customName || customFields.length === 0}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer whitespace-nowrap disabled:opacity-40 hover:bg-gray-50">
              <div className="w-4 h-4 flex items-center justify-center"><i className="ri-play-circle-line text-sm"></i></div>
              Generate Now
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
