'use client';
import { useState } from 'react';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

const SAVED_REPORTS = [
  { id: 'r1', name: 'Monthly Headcount by Department', module: 'Employees', type: 'Bar', shared: true, schedule: 'Monthly', lastRun: '2026-04-01', owner: 'System Administrator' },
  { id: 'r2', name: 'Q1 2026 Training Completion Rate', module: 'Training', type: 'Pie', shared: true, schedule: 'Quarterly', lastRun: '2026-04-01', owner: 'HR Manager' },
  { id: 'r3', name: 'Leave Utilization by Department', module: 'Leave', type: 'Bar', shared: false, schedule: 'Weekly', lastRun: '2026-04-07', owner: 'HR Manager' },
  { id: 'r4', name: 'Turnover Rate 12-Month Trend', module: 'Termination', type: 'Line', shared: true, schedule: 'Monthly', lastRun: '2026-04-01', owner: 'System Administrator' },
  { id: 'r5', name: 'Open Disciplinary Cases by Severity', module: 'Disciplinary', type: 'Pie', shared: false, schedule: 'None', lastRun: '2026-04-10', owner: 'HR Manager' },
];

const MODULES = ['Employees', 'Leave', 'Training', 'Disciplinary', 'Termination', 'Performance', 'Payroll', 'Grading'];
const CHART_TYPES = ['Bar', 'Line', 'Pie', 'Table'];

const CHART_DATA = {
  Bar: [
    { name: 'Finance', value: 8 }, { name: 'ICT', value: 6 }, { name: 'Procurement', value: 5 },
    { name: 'M&E', value: 7 }, { name: 'Communication', value: 4 }, { name: 'Transport', value: 3 },
  ],
  Line: [
    { month: 'Nov', rate: 3.2 }, { month: 'Dec', rate: 2.8 }, { month: 'Jan', rate: 4.1 },
    { month: 'Feb', rate: 3.5 }, { month: 'Mar', rate: 2.9 }, { month: 'Apr', rate: 3.7 },
  ],
  Pie: [
    { name: 'Approved', value: 28 }, { name: 'Pending', value: 12 }, { name: 'Rejected', value: 5 }, { name: 'Expired', value: 3 },
  ],
};

const PIE_COLORS = ['#b828a0', '#8a1e78', '#e879c0', '#f3b8e8'];

export default function ReportBuilderTab() {
  const [activeView, setActiveView] = useState<'builder' | 'saved'>('saved');
  const [selectedModule, setSelectedModule] = useState('Employees');
  const [selectedChart, setSelectedChart] = useState('Bar');
  const [reportName, setReportName] = useState('');
  const [schedule, setSchedule] = useState('None');
  const [shareReport, setShareReport] = useState(false);
  const [previewShown, setPreviewShown] = useState(false);
  const [savedReports, setSavedReports] = useState(SAVED_REPORTS);
  const [toast, setToast] = useState('');

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const handleSaveReport = () => {
    if (!reportName.trim()) return;
    const newReport = {
      id: `r${Date.now()}`, name: reportName, module: selectedModule, type: selectedChart,
      shared: shareReport, schedule, lastRun: new Date().toISOString().split('T')[0], owner: 'System Administrator',
    };
    setSavedReports(prev => [newReport, ...prev]);
    showToast(`Report "${reportName}" saved!`);
    setReportName('');
    setActiveView('saved');
  };

  const handleDeleteReport = (id: string) => {
    setSavedReports(prev => prev.filter(r => r.id !== id));
  };

  const renderPreviewChart = () => {
    if (selectedChart === 'Bar') {
      return (
        <ResponsiveContainer width="100%" height={250}>
          <BarChart data={CHART_DATA.Bar}>
            <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
            <XAxis dataKey="name" tick={{ fontSize: 11 }} />
            <YAxis tick={{ fontSize: 11 }} />
            <Tooltip />
            <Bar dataKey="value" fill="#b828a0" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      );
    }
    if (selectedChart === 'Line') {
      return (
        <ResponsiveContainer width="100%" height={250}>
          <LineChart data={CHART_DATA.Line}>
            <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
            <XAxis dataKey="month" tick={{ fontSize: 11 }} />
            <YAxis tick={{ fontSize: 11 }} />
            <Tooltip />
            <Line type="monotone" dataKey="rate" stroke="#b828a0" strokeWidth={2} dot={{ fill: '#b828a0', r: 4 }} />
          </LineChart>
        </ResponsiveContainer>
      );
    }
    if (selectedChart === 'Pie') {
      return (
        <ResponsiveContainer width="100%" height={250}>
          <PieChart>
            <Pie data={CHART_DATA.Pie} cx="50%" cy="50%" outerRadius={90} dataKey="value" label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}>
              {CHART_DATA.Pie.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
            </Pie>
            <Tooltip />
          </PieChart>
        </ResponsiveContainer>
      );
    }
    return (
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead><tr className="border-b">{['Department', 'Count', 'Percentage'].map(h => <th key={h} className="text-left py-2 px-3 text-xs font-semibold text-gray-500">{h}</th>)}</tr></thead>
          <tbody>{CHART_DATA.Bar.map((r, i) => <tr key={i} className="border-b border-gray-50"><td className="py-2 px-3 text-sm text-gray-700">{r.name}</td><td className="py-2 px-3 text-sm font-semibold">{r.value}</td><td className="py-2 px-3 text-sm text-gray-500">{Math.round(r.value / 33 * 100)}%</td></tr>)}</tbody>
        </table>
      </div>
    );
  };

  return (
    <div className="space-y-5">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
          <div className="w-5 h-5 flex items-center justify-center"><i className="ri-checkbox-circle-line text-lg"></i></div>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="flex items-center justify-between">
        <div className="flex gap-2 p-1 bg-gray-100 rounded-xl">
          {[{ key: 'saved', label: 'Saved Reports', icon: 'ri-bookmark-line' }, { key: 'builder', label: 'Report Builder', icon: 'ri-tools-line' }].map(t => (
            <button key={t.key} onClick={() => setActiveView(t.key as any)}
              className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${activeView === t.key ? 'bg-white text-gray-800 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
              <div className="w-4 h-4 flex items-center justify-center"><i className={`${t.icon} text-sm`}></i></div>
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {activeView === 'saved' && (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold text-gray-800">Saved Reports ({savedReports.length})</h3>
            <button onClick={() => setActiveView('builder')} className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
              <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line text-sm"></i></div>
              New Report
            </button>
          </div>
          <div className="space-y-2">
            {savedReports.map(r => (
              <div key={r.id} className="flex items-center gap-4 p-4 border border-gray-100 rounded-xl hover:bg-gray-50/50 transition-colors">
                <div className="w-10 h-10 flex items-center justify-center rounded-xl bg-pink-50 flex-shrink-0">
                  <i className={`${r.type === 'Bar' ? 'ri-bar-chart-line' : r.type === 'Line' ? 'ri-line-chart-line' : r.type === 'Pie' ? 'ri-pie-chart-line' : 'ri-table-line'} text-xl`} style={{ color: '#b828a0' }}></i>
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-semibold text-gray-800">{r.name}</p>
                    {r.shared && <span className="px-1.5 py-0.5 rounded text-xs bg-blue-100 text-blue-700 font-medium">Shared</span>}
                    {r.schedule !== 'None' && <span className="px-1.5 py-0.5 rounded text-xs bg-amber-100 text-amber-700 font-medium">{r.schedule}</span>}
                  </div>
                  <div className="flex items-center gap-2 mt-0.5 text-xs text-gray-400">
                    <span>{r.module}</span>
                    <span>•</span>
                    <span>{r.type} chart</span>
                    <span>•</span>
                    <span>Last run: {r.lastRun}</span>
                    <span>•</span>
                    <span>By {r.owner}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2 flex-shrink-0">
                  <button onClick={() => showToast(`Running "${r.name}"...`)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                    <i className="ri-play-line text-xs"></i> Run
                  </button>
                  <button onClick={() => showToast(`Exporting "${r.name}"...`)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                    <i className="ri-download-line text-xs"></i> Export
                  </button>
                  <button onClick={() => handleDeleteReport(r.id)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 text-red-400 cursor-pointer">
                    <i className="ri-delete-bin-line text-sm"></i>
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {activeView === 'builder' && (
        <div className="grid grid-cols-5 gap-5">
          <div className="col-span-2 space-y-4">
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
              <h3 className="font-bold text-gray-800 mb-4">Report Configuration</h3>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Report Name</label>
                  <input value={reportName} onChange={e => setReportName(e.target.value)}
                    className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" placeholder="e.g. Monthly Leave Summary" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-2">Data Module</label>
                  <div className="grid grid-cols-2 gap-2">
                    {MODULES.map(m => (
                      <button key={m} onClick={() => setSelectedModule(m)}
                        className={`px-3 py-2 rounded-xl text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${selectedModule === m ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                        style={selectedModule === m ? { background: '#b828a0' } : {}}>
                        {m}
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-2">Chart Type</label>
                  <div className="grid grid-cols-4 gap-2">
                    {CHART_TYPES.map(ct => (
                      <button key={ct} onClick={() => setSelectedChart(ct)}
                        className={`p-2.5 rounded-xl border-2 cursor-pointer transition-all text-center ${selectedChart === ct ? 'border-pink-400 bg-pink-50' : 'border-gray-100 hover:border-gray-200'}`}>
                        <div className="w-5 h-5 flex items-center justify-center mx-auto mb-1">
                          <i className={`${ct === 'Bar' ? 'ri-bar-chart-line' : ct === 'Line' ? 'ri-line-chart-line' : ct === 'Pie' ? 'ri-pie-chart-line' : 'ri-table-line'} text-lg`} style={{ color: selectedChart === ct ? '#b828a0' : '#9ca3af' }}></i>
                        </div>
                        <p className="text-xs font-medium text-gray-600">{ct}</p>
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-2">Schedule</label>
                  <div className="flex flex-wrap gap-2">
                    {['None', 'Daily', 'Weekly', 'Monthly', 'Quarterly'].map(s => (
                      <button key={s} onClick={() => setSchedule(s)}
                        className={`px-3 py-1.5 rounded-xl text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${schedule === s ? 'text-white' : 'bg-gray-100 text-gray-600'}`}
                        style={schedule === s ? { background: '#b828a0' } : {}}>
                        {s}
                      </button>
                    ))}
                  </div>
                </div>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input type="checkbox" checked={shareReport} onChange={e => setShareReport(e.target.checked)} className="cursor-pointer" />
                  <span className="text-sm text-gray-600">Share with all HR users</span>
                </label>
                <div className="flex gap-2 pt-2">
                  <button onClick={() => setPreviewShown(true)} className="flex-1 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer hover:bg-gray-50">
                    Preview
                  </button>
                  <button onClick={handleSaveReport} className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer" style={{ background: '#b828a0' }}>
                    Save Report
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="col-span-3">
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-bold text-gray-800">Report Preview</h3>
                <div className="flex items-center gap-2">
                  <span className="text-xs text-gray-400">{selectedModule} • {selectedChart} chart</span>
                  {previewShown && (
                    <button onClick={() => showToast('Exporting preview...')} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-gray-200 text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                      <i className="ri-download-line text-xs"></i> Export
                    </button>
                  )}
                </div>
              </div>
              {previewShown ? (
                renderPreviewChart()
              ) : (
                <div className="flex flex-col items-center justify-center h-64 text-gray-400">
                  <div className="w-16 h-16 flex items-center justify-center mb-3"><i className="ri-bar-chart-box-line text-5xl"></i></div>
                  <p className="text-sm">Configure your report and click Preview</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
