'use client';
import { useState } from 'react';
import { exportLogs, ExportLog, ExportStatus, csvSampleRows } from './payrollData';

const statusConfig: Record<ExportStatus, { color: string; bg: string; icon: string }> = {
  Success: { color: 'text-green-700', bg: 'bg-green-100', icon: 'ri-checkbox-circle-line' },
  Failed: { color: 'text-red-700', bg: 'bg-red-100', icon: 'ri-close-circle-line' },
  Partial: { color: 'text-yellow-700', bg: 'bg-yellow-100', icon: 'ri-error-warning-line' },
  Pending: { color: 'text-blue-700', bg: 'bg-blue-100', icon: 'ri-time-line' },
};

const csvColumns = ['employee_id','full_name','department','grade','status','basic_salary','housing_allowance','transport_allowance','other_allowances','total_deductions','leave_without_pay_days','overtime_hours','salary_deduction','bonus','advance_recovery','effective_month'];

export default function ExportTab() {
  const [method, setMethod] = useState<'File-Based' | 'API'>('File-Based');
  const [month, setMonth] = useState('2026-04');
  const [exporting, setExporting] = useState(false);
  const [exported, setExported] = useState(false);
  const [showSample, setShowSample] = useState(false);

  const handleExport = () => {
    setExporting(true);
    setTimeout(() => { setExporting(false); setExported(true); }, 2200);
  };

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 gap-5">
        <div className="bg-white rounded-xl border border-gray-200 p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Export Configuration</h3>
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-2">Export Month</label>
              <input type="month" value={month} onChange={e => setMonth(e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-2">Integration Method</label>
              <div className="grid grid-cols-2 gap-2">
                {(['File-Based', 'API'] as const).map(m => (
                  <button key={m} onClick={() => setMethod(m)} className={`py-3 rounded-xl border-2 text-sm cursor-pointer transition-all ${method === m ? 'border-pink-500 bg-pink-50 text-pink-700 font-semibold' : 'border-gray-200 text-gray-600 hover:border-gray-300'}`}>
                    <div className="w-5 h-5 flex items-center justify-center mx-auto mb-1">
                      <i className={`${m === 'File-Based' ? 'ri-file-excel-line' : 'ri-code-s-slash-line'} text-lg`}></i>
                    </div>
                    {m}
                  </button>
                ))}
              </div>
            </div>
            {method === 'File-Based' && (
              <div className="bg-gray-50 rounded-xl p-3 space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">Format</span><span className="font-medium">CSV (UTF-8)</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Encryption</span><span className="font-medium">AES-256</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Transfer</span><span className="font-medium">Secure SFTP</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Checksum</span><span className="font-medium">MD5 Hash</span></div>
                <div className="flex justify-between"><span className="text-gray-500">File Name</span><span className="font-mono text-xs">Payroll_{month.replace('-','')}_HHMMSS.csv</span></div>
              </div>
            )}
            {method === 'API' && (
              <div className="bg-gray-50 rounded-xl p-3 space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">Endpoint</span><span className="font-mono text-xs">POST /api/payroll/monthly-variables</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Auth</span><span className="font-medium">API Key + JWT</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Rate Limit</span><span className="font-medium">1,000 req/min</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Webhook</span><span className="font-medium text-green-600">Enabled</span></div>
              </div>
            )}
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-2">Include Data Sections</label>
              <div className="space-y-2">
                {['Employee Master Data', 'Salary Structure', 'Monthly Variables', 'Leave Data', 'Disciplinary Deductions'].map(s => (
                  <label key={s} className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" defaultChecked className="accent-pink-600" />
                    <span className="text-sm text-gray-700">{s}</span>
                  </label>
                ))}
              </div>
            </div>
            <button onClick={handleExport} disabled={exporting} className="w-full py-2.5 bg-pink-600 text-white rounded-xl text-sm font-semibold hover:bg-pink-700 cursor-pointer disabled:opacity-60 whitespace-nowrap transition-all">
              {exporting ? 'Exporting...' : 'Generate & Export Payroll File'}
            </button>
            {exported && (
              <div className="bg-green-50 border border-green-200 rounded-xl p-3 flex items-center gap-2">
                <div className="w-4 h-4 flex items-center justify-center text-green-600"><i className="ri-checkbox-circle-fill text-base"></i></div>
                <p className="text-sm text-green-700 font-medium">Export successful! File: Payroll_{month.replace('-','')}_143022.csv</p>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-4">
          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-semibold text-gray-800">API Endpoints Reference</h3>
            </div>
            <div className="space-y-3">
              {[
                { method: 'POST', path: '/api/payroll/employees', desc: 'Send employee master data' },
                { method: 'POST', path: '/api/payroll/salary-changes', desc: 'Send salary adjustments' },
                { method: 'POST', path: '/api/payroll/monthly-variables', desc: 'Send monthly variable data' },
                { method: 'GET', path: '/api/payroll/confirmation', desc: 'Retrieve payroll receipt' },
              ].map((ep, i) => (
                <div key={i} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                  <span className={`text-xs font-bold px-2 py-0.5 rounded ${ep.method === 'GET' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'}`}>{ep.method}</span>
                  <div>
                    <p className="text-xs font-mono text-gray-700">{ep.path}</p>
                    <p className="text-xs text-gray-500">{ep.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <h3 className="font-semibold text-gray-800 mb-3">Error Handling Policy</h3>
            <div className="space-y-2 text-sm">
              {[
                { icon: 'ri-repeat-line', text: 'Retry: 3 attempts, 5 minutes apart' },
                { icon: 'ri-mail-line', text: 'Alert: HR + Payroll notified on failure' },
                { icon: 'ri-file-list-line', text: 'Log: Success/failure per record exported' },
                { icon: 'ri-edit-line', text: 'Manual override: Correct and re-export' },
                { icon: 'ri-delete-bin-line', text: 'File retention: Deleted after 90 days' },
              ].map((item, i) => (
                <div key={i} className="flex items-center gap-2 text-gray-600">
                  <div className="w-4 h-4 flex items-center justify-center text-pink-500"><i className={`${item.icon} text-sm`}></i></div>
                  {item.text}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
          <div>
            <h3 className="font-semibold text-gray-800">Sample Export File Structure</h3>
            <p className="text-xs text-gray-500 mt-0.5">Preview of April 2026 payroll CSV</p>
          </div>
          <button onClick={() => setShowSample(!showSample)} className="text-sm text-pink-600 hover:underline cursor-pointer whitespace-nowrap">{showSample ? 'Hide' : 'Show'} Preview</button>
        </div>
        {showSample && (
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead>
                <tr className="bg-pink-50 border-b border-pink-100">
                  {csvColumns.map(col => (
                    <th key={col} className="px-3 py-2 text-left text-pink-700 font-mono font-semibold whitespace-nowrap">{col}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {csvSampleRows.map((row, i) => (
                  <tr key={i} className="border-b border-gray-100 hover:bg-gray-50">
                    {csvColumns.map(col => (
                      <td key={col} className="px-3 py-2 text-gray-600 font-mono whitespace-nowrap">{(row as Record<string,string>)[col] || '-'}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div className="px-5 py-4 border-b border-gray-200">
          <h3 className="font-semibold text-gray-800">Export Audit Log</h3>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Export ID</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Date & Time</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Month</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Exported By</th>
              <th className="text-center px-4 py-3 text-gray-600 font-semibold">Records</th>
              <th className="text-center px-4 py-3 text-gray-600 font-semibold">Method</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">File</th>
              <th className="text-center px-4 py-3 text-gray-600 font-semibold">Status</th>
            </tr>
          </thead>
          <tbody>
            {exportLogs.map(log => {
              const cfg = statusConfig[log.status];
              return (
                <tr key={log.id} className="border-b border-gray-100 hover:bg-gray-50">
                  <td className="px-4 py-3 font-mono text-xs text-pink-700 font-semibold">{log.id}</td>
                  <td className="px-4 py-3 text-gray-600 text-xs">{log.exportDate}</td>
                  <td className="px-4 py-3 text-gray-700 font-medium">{log.month}</td>
                  <td className="px-4 py-3 text-gray-600">{log.exportedBy}</td>
                  <td className="px-4 py-3 text-center">
                    <span className="text-gray-700 font-semibold">{log.successRecords}</span>
                    {log.failedRecords > 0 && <span className="text-red-500 text-xs"> (-{log.failedRecords})</span>}
                    <span className="text-gray-400 text-xs"> /{log.totalRecords}</span>
                  </td>
                  <td className="px-4 py-3 text-center"><span className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded">{log.method}</span></td>
                  <td className="px-4 py-3 font-mono text-xs text-gray-500 truncate max-w-xs">{log.fileName}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold w-fit mx-auto ${cfg.bg} ${cfg.color}`}>
                      <i className={`${cfg.icon} text-xs`}></i>
                      {log.status}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
