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

interface Vendor {
  id: number;
  name: string;
  contact: string;
  email: string;
  serviceType: string;
  contractStart: string;
  contractEnd: string;
  rating: number;
  status: 'Active' | 'Expired' | 'Pending';
}

const initialVendors: Vendor[] = [
  { id: 1, name: 'Kenya Institute of Management', contact: '+254 722 345 678', email: 'training@kim.ac.ke', serviceType: 'Training Provider', contractStart: '2025-01-01', contractEnd: '2026-12-31', rating: 5, status: 'Active' },
  { id: 2, name: 'Corporate Staffing Services', contact: '+254 733 456 789', email: 'recruit@css.co.ke', serviceType: 'Recruiter', contractStart: '2025-03-01', contractEnd: '2026-02-28', rating: 4, status: 'Active' },
  { id: 3, name: 'Jubilee Health Insurance', contact: '+254 711 567 890', email: 'corporate@jubilee.co.ke', serviceType: 'Benefits Vendor', contractStart: '2025-01-01', contractEnd: '2025-12-31', rating: 4, status: 'Expired' },
  { id: 4, name: 'KPMG East Africa', contact: '+254 704 678 901', email: 'advisory@kpmg.co.ke', serviceType: 'HR Consultant', contractStart: '2026-01-15', contractEnd: '2026-06-30', rating: 5, status: 'Active' },
  { id: 5, name: 'SafariCom Business Solutions', contact: '+254 722 789 012', email: 'b2b@safaricom.co.ke', serviceType: 'Technology Vendor', contractStart: '2025-06-01', contractEnd: '2027-05-31', rating: 3, status: 'Active' },
  { id: 6, name: 'Deloitte Training Institute', contact: '+254 700 890 123', email: 'training@deloitte.com', serviceType: 'Training Provider', contractStart: '2026-02-01', contractEnd: '2026-12-31', rating: 5, status: 'Pending' },
];

const SERVICE_TYPES = ['All', 'Training Provider', 'Recruiter', 'Benefits Vendor', 'HR Consultant', 'Technology Vendor'];

const statusColors: Record<string, string> = {
  Active: 'bg-green-100 text-green-700',
  Expired: 'bg-red-100 text-red-600',
  Pending: 'bg-amber-100 text-amber-700',
};

function StarRating({ value }: { value: number }) {
  return (
    <div className="flex gap-0.5">
      {[1, 2, 3, 4, 5].map(i => (
        <div key={i} className="w-3 h-3 flex items-center justify-center">
          <i className={`${i <= value ? 'ri-star-fill' : 'ri-star-line'} text-xs text-yellow-400`}></i>
        </div>
      ))}
    </div>
  );
}

interface VendorModalProps { vendor?: Vendor | null; onClose: () => void; onSave: (v: Omit<Vendor, 'id'>) => void; }
function VendorModal({ vendor, onClose, onSave }: VendorModalProps) {
  const [form, setForm] = useState({
    name: vendor?.name || '', contact: vendor?.contact || '', email: vendor?.email || '',
    serviceType: vendor?.serviceType || 'Training Provider', contractStart: vendor?.contractStart || '',
    contractEnd: vendor?.contractEnd || '', rating: vendor?.rating || 3, status: vendor?.status || 'Active' as Vendor['status'],
  });
  return (
    <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-lg p-6">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-base font-bold text-gray-800">{vendor ? 'Edit Vendor' : 'Add Vendor'}</h3>
          <button onClick={onClose} 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="grid grid-cols-2 gap-4">
          <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-1">Vendor / Provider Name</label>
            <input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Organization name" className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
          {[{ l: 'Contact Phone', k: 'contact' }, { l: 'Email', k: 'email' }].map(f => (
            <div key={f.k}><label className="text-xs font-semibold text-gray-600 block mb-1">{f.l}</label>
              <input value={(form as any)[f.k]} onChange={e => setForm(p => ({ ...p, [f.k]: e.target.value }))} className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" /></div>
          ))}
          <div className="col-span-2"><label className="text-xs font-semibold text-gray-600 block mb-1">Service Type</label>
            <div className="flex gap-2 flex-wrap">
              {SERVICE_TYPES.slice(1).map(t => (
                <button key={t} onClick={() => setForm(f => ({ ...f, serviceType: t }))}
                  className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${form.serviceType === t ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                  style={form.serviceType === t ? { background: '#b828a0' } : {}}>{t}</button>
              ))}
            </div>
          </div>
          {[{ l: 'Contract Start', k: 'contractStart' }, { l: 'Contract End', k: 'contractEnd' }].map(f => (
            <div key={f.k}><label className="text-xs font-semibold text-gray-600 block mb-1">{f.l}</label>
              <input type="date" value={(form as any)[f.k]} onChange={e => setForm(p => ({ ...p, [f.k]: e.target.value }))} 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">Rating</label>
            <div className="flex gap-1">
              {[1, 2, 3, 4, 5].map(i => (
                <button key={i} onClick={() => setForm(f => ({ ...f, rating: i }))} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                  <i className={`${i <= form.rating ? 'ri-star-fill' : 'ri-star-line'} text-xl text-yellow-400`}></i>
                </button>
              ))}
            </div>
          </div>
          <div><label className="text-xs font-semibold text-gray-600 block mb-1">Status</label>
            <div className="flex gap-2">
              {(['Active', 'Pending', 'Expired'] as Vendor['status'][]).map(s => (
                <button key={s} onClick={() => setForm(f => ({ ...f, status: s }))}
                  className={`px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${form.status === s ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                  style={form.status === s ? { background: '#b828a0' } : {}}>{s}</button>
              ))}
            </div>
          </div>
        </div>
        <div className="flex gap-3 mt-6">
          <button onClick={onClose} 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={() => { onSave(form); onClose(); }} className="flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
            {vendor ? 'Save Changes' : 'Add Vendor'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default function VendorsSection() {
  const [vendors, setVendors] = useState<Vendor[]>(initialVendors);
  const [filter, setFilter] = useState('All');
  const [modal, setModal] = useState(false);
  const [editing, setEditing] = useState<Vendor | null>(null);
  const [delTarget, setDelTarget] = useState<Vendor | null>(null);
  const [toast, setToast] = useState('');

  const filtered = filter === 'All' ? vendors : vendors.filter(v => v.serviceType === filter);

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {modal && <VendorModal vendor={editing} onClose={() => { setModal(false); setEditing(null); }}
        onSave={data => {
          if (editing) setVendors(vs => vs.map(v => v.id === editing.id ? { ...v, ...data } : v));
          else setVendors(vs => [...vs, { ...data, id: Date.now() }]);
          setToast(editing ? 'Vendor updated' : 'Vendor added');
        }} />}
      {delTarget && <ConfirmDialog title="Remove Vendor" message={`Remove "${delTarget.name}" from the vendor list?`}
        onConfirm={() => { setVendors(vs => vs.filter(v => v.id !== delTarget.id)); setDelTarget(null); setToast('Vendor removed'); }}
        onCancel={() => setDelTarget(null)} />}

      <SectionHeader icon="ri-building-2-line" title="Vendors & Service Providers" desc="Manage training providers, recruiters, and benefit vendors"
        action={<button onClick={() => { setEditing(null); 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-add-line text-sm"></i></div> Add Vendor
        </button>} />

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

      <div className="grid grid-cols-1 gap-3">
        {filtered.map(v => (
          <div key={v.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-11 h-11 rounded-xl bg-pink-50 flex items-center justify-center flex-shrink-0">
                  <i className="ri-building-2-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">{v.name}</p>
                    <span className={`text-xs px-2.5 py-0.5 rounded-full font-medium ${statusColors[v.status]}`}>{v.status}</span>
                  </div>
                  <p className="text-xs text-gray-500 mt-0.5">{v.serviceType}</p>
                  <div className="flex items-center gap-4 mt-1.5">
                    <div className="flex items-center gap-1 text-xs text-gray-500">
                      <div className="w-3 h-3 flex items-center justify-center"><i className="ri-phone-line text-xs"></i></div>
                      {v.contact}
                    </div>
                    <div className="flex items-center gap-1 text-xs text-gray-500">
                      <div className="w-3 h-3 flex items-center justify-center"><i className="ri-mail-line text-xs"></i></div>
                      {v.email}
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex flex-col items-end gap-2">
                <div className="flex items-center gap-1">
                  <button onClick={() => { setEditing(v); setModal(true); }} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer"><i className="ri-edit-2-line text-blue-400 text-sm"></i></button>
                  <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-green-50 cursor-pointer"><i className="ri-attachment-2 text-green-500 text-sm"></i></button>
                  <button onClick={() => setDelTarget(v)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer"><i className="ri-delete-bin-line text-red-400 text-sm"></i></button>
                </div>
                <StarRating value={v.rating} />
              </div>
            </div>
            <div className="mt-3 pt-3 border-t border-gray-50 flex items-center gap-6 text-xs text-gray-500">
              <div className="flex items-center gap-1"><div className="w-3 h-3 flex items-center justify-center"><i className="ri-calendar-line text-xs"></i></div>Contract: {v.contractStart} → {v.contractEnd}</div>
              <button className="flex items-center gap-1 font-medium cursor-pointer" style={{ color: '#b828a0' }}>
                <div className="w-3 h-3 flex items-center justify-center"><i className="ri-file-text-line text-xs"></i></div>
                View SLA / Contract
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
