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

interface Policy {
  id: number;
  title: string;
  category: string;
  version: string;
  updatedBy: string;
  updatedAt: string;
  status: 'Active' | 'Archived' | 'Draft';
  acknowledged: number;
  total: number;
}

const initialPolicies: Policy[] = [
  { id: 1, title: 'Code of Conduct', category: 'Code of Conduct', version: 'v3.2', updatedBy: 'Jane Wambua', updatedAt: '2026-01-10', status: 'Active', acknowledged: 238, total: 248 },
  { id: 2, title: 'Annual Leave Policy', category: 'Leave Policy', version: 'v2.1', updatedBy: 'John Mwangi', updatedAt: '2025-11-05', status: 'Active', acknowledged: 201, total: 248 },
  { id: 3, title: 'Disciplinary Code & Procedure', category: 'Disciplinary Code', version: 'v4.0', updatedBy: 'Susan Kamau', updatedAt: '2025-12-20', status: 'Active', acknowledged: 195, total: 248 },
  { id: 4, title: 'ICT & Information Security Policy', category: 'ICT Policy', version: 'v1.5', updatedBy: 'David Otieno', updatedAt: '2026-02-14', status: 'Active', acknowledged: 180, total: 248 },
  { id: 5, title: 'Anti-Harassment & POSH Policy', category: 'Code of Conduct', version: 'v2.0', updatedBy: 'Faith Njoroge', updatedAt: '2025-09-30', status: 'Active', acknowledged: 220, total: 248 },
  { id: 6, title: 'Travel & Per Diem Policy', category: 'Finance Policy', version: 'v1.3', updatedBy: 'Peter Kariuki', updatedAt: '2025-08-01', status: 'Archived', acknowledged: 145, total: 248 },
  { id: 7, title: 'Recruitment & Selection Policy', category: 'HR Policy', version: 'v0.1', updatedBy: 'Grace Muthoni', updatedAt: '2026-03-22', status: 'Draft', acknowledged: 0, total: 248 },
];

const CATEGORIES = ['All', 'Code of Conduct', 'Leave Policy', 'Disciplinary Code', 'ICT Policy', 'Finance Policy', 'HR Policy'];

const statusColors: Record<string, string> = {
  Active: 'bg-green-100 text-green-700',
  Archived: 'bg-gray-100 text-gray-500',
  Draft: 'bg-amber-100 text-amber-700',
};

export default function PoliciesSection() {
  const [policies, setPolicies] = useState<Policy[]>(initialPolicies);
  const [filter, setFilter] = useState('All');
  const [toast, setToast] = useState('');
  const [delTarget, setDelTarget] = useState<Policy | null>(null);
  const [modal, setModal] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [ackModal, setAckModal] = useState<Policy | null>(null);

  const filtered = filter === 'All' ? policies : policies.filter(p => p.category === filter);

  const handleUpload = () => {
    setUploading(true);
    setTimeout(() => { setUploading(false); setToast('Policy document uploaded successfully'); setModal(false); }, 1500);
  };

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {delTarget && <ConfirmDialog title="Archive Policy" message={`Archive "${delTarget.title}"? It will be moved to archived versions.`}
        confirmLabel="Archive" danger={false}
        onConfirm={() => { setPolicies(ps => ps.map(p => p.id === delTarget.id ? { ...p, status: 'Archived' } : p)); setDelTarget(null); setToast('Policy archived'); }}
        onCancel={() => setDelTarget(null)} />}

      {modal && (
        <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-md p-6">
            <div className="flex items-center justify-between mb-5">
              <h3 className="text-base font-bold text-gray-800">Upload Policy Document</h3>
              <button onClick={() => setModal(false)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer"><i className="ri-close-line text-gray-500"></i></button>
            </div>
            <div className="space-y-4">
              {[{ label: 'Policy Title', placeholder: 'e.g. Code of Conduct' }, { label: 'Version', placeholder: 'e.g. v1.0' }].map(f => (
                <div key={f.label}>
                  <label className="text-xs font-semibold text-gray-600 block mb-1">{f.label}</label>
                  <input placeholder={f.placeholder} className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none" />
                </div>
              ))}
              <div>
                <label className="text-xs font-semibold text-gray-600 block mb-1">Category</label>
                <div className="relative">
                  <select className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none appearance-none pr-8 cursor-pointer">
                    {CATEGORIES.slice(1).map(c => <option key={c}>{c}</option>)}
                  </select>
                  <div className="w-5 h-5 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"><i className="ri-arrow-down-s-line text-gray-400"></i></div>
                </div>
              </div>
              <div className="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center cursor-pointer hover:border-pink-300 transition-colors">
                <div className="w-8 h-8 flex items-center justify-center mx-auto mb-2" style={{ color: '#b828a0' }}><i className="ri-file-upload-line text-3xl"></i></div>
                <p className="text-sm text-gray-600">Click to select PDF / Word document</p>
                <p className="text-xs text-gray-400 mt-1">Max file size: 10MB</p>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button onClick={() => setModal(false)} className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleUpload}
                className="flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap flex items-center justify-center gap-2"
                style={{ background: '#b828a0' }}>
                {uploading ? <><i className="ri-loader-4-line animate-spin"></i> Uploading...</> : 'Upload Policy'}
              </button>
            </div>
          </div>
        </div>
      )}

      {ackModal && (
        <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">Acknowledgment Tracker</h3>
              <button onClick={() => setAckModal(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">{ackModal.title} — {ackModal.version}</p>
            <div className="mb-4">
              <div className="flex justify-between text-xs mb-1">
                <span className="text-gray-500">Acknowledged</span>
                <span className="font-bold" style={{ color: '#b828a0' }}>{ackModal.acknowledged}/{ackModal.total}</span>
              </div>
              <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                <div className="h-full rounded-full transition-all" style={{ width: `${(ackModal.acknowledged / ackModal.total) * 100}%`, background: '#b828a0' }}></div>
              </div>
              <p className="text-xs text-gray-400 mt-1">{ackModal.total - ackModal.acknowledged} employees pending signature</p>
            </div>
            <button onClick={() => setToast('Reminder sent to pending employees')} className="w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
              Send Reminder to Pending
            </button>
          </div>
        </div>
      )}

      <SectionHeader icon="ri-file-list-3-line" title="Company Policies Repository" desc="Upload, version-control, and track policy acknowledgments"
        action={<button onClick={() => setModal(true)} className="flex items-center gap-2 px-4 py-2 rounded-xl text-white text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-upload-2-line text-sm"></i></div> Upload Policy
        </button>} />

      <div className="flex gap-2 mb-4 flex-wrap">
        {CATEGORIES.map(c => (
          <button key={c} onClick={() => setFilter(c)}
            className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${filter === c ? 'text-white border-transparent' : 'bg-white text-gray-600 border-gray-200'}`}
            style={filter === c ? { background: '#b828a0' } : {}}>
            {c}
          </button>
        ))}
      </div>

      <div className="space-y-3">
        {filtered.map(policy => (
          <div key={policy.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 flex items-center justify-center flex-shrink-0 bg-pink-50">
                  <i className="ri-file-pdf-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">{policy.title}</p>
                    <span className="text-xs font-mono px-2 py-0.5 rounded-full bg-gray-100 text-gray-500">{policy.version}</span>
                    <span className={`text-xs px-2.5 py-0.5 rounded-full font-medium ${statusColors[policy.status]}`}>{policy.status}</span>
                  </div>
                  <p className="text-xs text-gray-500 mt-0.5">{policy.category} · Updated by {policy.updatedBy} on {policy.updatedAt}</p>
                </div>
              </div>
              <div className="flex items-center gap-1">
                <button onClick={() => setAckModal(policy)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-pink-50 text-xs font-medium cursor-pointer whitespace-nowrap" style={{ color: '#b828a0' }}>
                  <i className="ri-checkbox-circle-line text-xs"></i> Acknowledgments
                </button>
                <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer"><i className="ri-download-2-line text-blue-400 text-sm"></i></button>
                {policy.status === 'Active' && (
                  <button onClick={() => setDelTarget(policy)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-amber-50 cursor-pointer"><i className="ri-archive-line text-amber-500 text-sm"></i></button>
                )}
              </div>
            </div>
            <div className="mt-3">
              <div className="flex items-center justify-between text-xs mb-1">
                <span className="text-gray-400">Employee acknowledgments</span>
                <span className="font-semibold" style={{ color: '#b828a0' }}>{policy.acknowledged}/{policy.total}</span>
              </div>
              <div className="w-full h-1.5 bg-gray-100 rounded-full overflow-hidden">
                <div className="h-full rounded-full" style={{ width: `${(policy.acknowledged / policy.total) * 100}%`, background: '#b828a0' }}></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
