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

interface NRule {
  id: number;
  entity: string;
  icon: string;
  prefix: string;
  suffix: string;
  includeYear: boolean;
  padLength: number;
  currentSeq: number;
  allowManual: boolean;
  preview: () => string;
}

const CURRENT_YEAR = '2026';

export default function NumberingRulesSection() {
  const [toast, setToast] = useState('');
  const [rules, setRules] = useState([
    { id: 1, entity: 'Employee ID', icon: 'ri-user-line', prefix: 'EMP', suffix: '', includeYear: true, padLength: 4, currentSeq: 1248, allowManual: false },
    { id: 2, entity: 'Department Code', icon: 'ri-building-2-line', prefix: 'DEPT', suffix: '', includeYear: false, padLength: 3, currentSeq: 7, allowManual: true },
    { id: 3, entity: 'Position Code', icon: 'ri-briefcase-line', prefix: 'POS', suffix: '', includeYear: false, padLength: 3, currentSeq: 42, allowManual: true },
    { id: 4, entity: 'Disciplinary Case No.', icon: 'ri-scales-3-line', prefix: 'DISC', suffix: '', includeYear: true, padLength: 4, currentSeq: 87, allowManual: false },
    { id: 5, entity: 'Leave Reference', icon: 'ri-calendar-check-line', prefix: 'LV', suffix: '', includeYear: true, padLength: 4, currentSeq: 3201, allowManual: false },
    { id: 6, entity: 'Training Reference', icon: 'ri-graduation-cap-line', prefix: 'TRN', suffix: '', includeYear: true, padLength: 4, currentSeq: 512, allowManual: false },
  ]);
  const [editing, setEditing] = useState<number | null>(null);

  const getPreview = (r: typeof rules[0]) => {
    const seq = String(r.currentSeq + 1).padStart(r.padLength, '0');
    const year = r.includeYear ? `-${CURRENT_YEAR}` : '';
    const suffix = r.suffix ? `-${r.suffix}` : '';
    return `${r.prefix}${year}-${seq}${suffix}`;
  };

  const update = (id: number, key: string, val: string | number | boolean) => {
    setRules(rs => rs.map(r => r.id === id ? { ...r, [key]: val } : r));
  };

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      <SectionHeader icon="ri-barcode-line" title="Numbering Rules" desc="Configure auto-generation formats for IDs and reference numbers"
        action={<button onClick={() => { setEditing(null); setToast('Rules saved successfully'); }}
          className="px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
          Save All Rules
        </button>} />

      <div className="space-y-4">
        {rules.map(rule => (
          <div key={rule.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden hover:-translate-y-0.5 transition-transform">
            <div className="flex items-center justify-between px-5 py-3 border-b border-gray-100" style={{ background: '#fdf0fb' }}>
              <div className="flex items-center gap-2">
                <div className="w-7 h-7 flex items-center justify-center" style={{ color: '#b828a0' }}><i className={`${rule.icon} text-base`}></i></div>
                <p className="text-sm font-bold text-gray-800">{rule.entity}</p>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500 font-mono bg-gray-100 px-3 py-1.5 rounded-lg">{getPreview(rule)}</span>
                <button onClick={() => setEditing(editing === rule.id ? null : rule.id)}
                  className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-pink-100 cursor-pointer">
                  <i className={`${editing === rule.id ? 'ri-arrow-up-s-line' : 'ri-settings-3-line'} text-sm`} style={{ color: '#b828a0' }}></i>
                </button>
              </div>
            </div>

            {editing === rule.id && (
              <div className="p-5">
                <div className="grid grid-cols-3 gap-4 mb-4">
                  {[{ label: 'Prefix', key: 'prefix', type: 'text' }, { label: 'Suffix (optional)', key: 'suffix', type: 'text' }, { label: 'Pad Length', key: 'padLength', type: 'number' }].map(f => (
                    <div key={f.key}>
                      <label className="text-xs font-semibold text-gray-600 block mb-1">{f.label}</label>
                      <input type={f.type} value={(rule as any)[f.key]} onChange={e => update(rule.id, f.key, f.type === 'number' ? +e.target.value : e.target.value)}
                        className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none font-mono" />
                    </div>
                  ))}
                </div>
                <div className="flex gap-6">
                  <label className="flex items-center gap-2 text-xs font-medium text-gray-600 cursor-pointer">
                    <button onClick={() => update(rule.id, 'includeYear', !rule.includeYear)}
                      className={`relative w-10 h-5 rounded-full transition-all cursor-pointer flex-shrink-0 ${rule.includeYear ? '' : 'bg-gray-200'}`}
                      style={rule.includeYear ? { background: '#b828a0' } : {}}>
                      <div className="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow-sm transition-all" style={rule.includeYear ? { left: '22px' } : { left: '2px' }}></div>
                    </button>
                    Include Year in format
                  </label>
                  <label className="flex items-center gap-2 text-xs font-medium text-gray-600 cursor-pointer">
                    <button onClick={() => update(rule.id, 'allowManual', !rule.allowManual)}
                      className={`relative w-10 h-5 rounded-full transition-all cursor-pointer flex-shrink-0 ${rule.allowManual ? '' : 'bg-gray-200'}`}
                      style={rule.allowManual ? { background: '#b828a0' } : {}}>
                      <div className="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow-sm transition-all" style={rule.allowManual ? { left: '22px' } : { left: '2px' }}></div>
                    </button>
                    Allow manual override
                  </label>
                </div>
                <div className="mt-4 p-3 bg-pink-50 rounded-xl">
                  <p className="text-xs text-gray-600">Preview: <span className="font-mono font-bold text-lg" style={{ color: '#b828a0' }}>{getPreview(rule)}</span></p>
                </div>
              </div>
            )}

            {editing !== rule.id && (
              <div className="px-5 py-3 flex items-center gap-6">
                <div><p className="text-xs text-gray-400">Format</p><p className="text-xs font-mono font-semibold text-gray-700">{rule.prefix}{rule.includeYear ? `-${CURRENT_YEAR}` : ''}-{'0'.repeat(rule.padLength)}{rule.suffix ? `-${rule.suffix}` : ''}</p></div>
                <div><p className="text-xs text-gray-400">Current Sequence</p><p className="text-xs font-semibold text-gray-700">#{rule.currentSeq}</p></div>
                <div><p className="text-xs text-gray-400">Manual Override</p>
                  <span className={`text-xs font-semibold ${rule.allowManual ? 'text-green-600' : 'text-red-500'}`}>{rule.allowManual ? 'Allowed' : 'Restricted'}</span>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
