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

interface Department {
  id: number;
  name: string;
  code: string;
  parent: string;
  positions: string[];
  headCount: number;
}

const initialDepts: Department[] = [
  { id: 1, name: 'Human Resources', code: 'HR-001', parent: 'Executive', positions: ['HR Manager', 'HR Officer', 'Recruiter'], headCount: 8 },
  { id: 2, name: 'Finance & Accounts', code: 'FIN-002', parent: 'Executive', positions: ['Finance Manager', 'Accountant', 'Cashier'], headCount: 12 },
  { id: 3, name: 'ICT & Systems', code: 'ICT-003', parent: 'Executive', positions: ['ICT Manager', 'Systems Analyst', 'Developer'], headCount: 6 },
  { id: 4, name: 'Program Management', code: 'PRG-004', parent: 'Executive', positions: ['Programs Director', 'Program Officer', 'M&E Specialist'], headCount: 15 },
  { id: 5, name: 'Regional Coordination', code: 'REG-005', parent: 'Program Management', positions: ['Regional Manager', 'Field Officer', 'Community Liaison'], headCount: 24 },
  { id: 6, name: 'Legal & Compliance', code: 'LGL-006', parent: 'Executive', positions: ['Legal Counsel', 'Compliance Officer'], headCount: 4 },
  { id: 7, name: 'Communications', code: 'COM-007', parent: 'Executive', positions: ['Communications Manager', 'PR Officer', 'Graphic Designer'], headCount: 5 },
];

interface DeptModalProps {
  dept?: Department | null;
  onClose: () => void;
  onSave: (d: Omit<Department, 'id' | 'headCount'>) => void;
}

function DeptModal({ dept, onClose, onSave }: DeptModalProps) {
  const [form, setForm] = useState({ name: dept?.name || '', code: dept?.code || '', parent: dept?.parent || 'Executive', positions: dept?.positions.join(', ') || '' });
  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-md p-6">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-base font-bold text-gray-800">{dept ? 'Edit Department' : 'Add Department'}</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="space-y-4">
          {[{ label: 'Department Name', key: 'name', placeholder: 'e.g. Finance & Accounts' }, { label: 'Department Code', key: 'code', placeholder: 'e.g. FIN-002' }].map(f => (
            <div key={f.key}>
              <label className="text-xs font-semibold text-gray-600 block mb-1">{f.label}</label>
              <input value={(form as any)[f.key]} onChange={e => setForm(p => ({ ...p, [f.key]: e.target.value }))}
                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">Parent Department</label>
            <div className="relative">
              <select value={form.parent} onChange={e => setForm(p => ({ ...p, parent: e.target.value }))} className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none appearance-none pr-8 cursor-pointer">
                <option>Executive</option>
                <option>Human Resources</option>
                <option>Finance & Accounts</option>
                <option>Program Management</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>
            <label className="text-xs font-semibold text-gray-600 block mb-1">Positions (comma separated)</label>
            <textarea value={form.positions} onChange={e => setForm(p => ({ ...p, positions: e.target.value }))}
              placeholder="e.g. Manager, Officer, Assistant" rows={2}
              className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none resize-none" maxLength={500}></textarea>
          </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 hover:bg-gray-50 cursor-pointer whitespace-nowrap">Cancel</button>
          <button onClick={() => { onSave({ name: form.name, code: form.code, parent: form.parent, positions: form.positions.split(',').map(s => s.trim()).filter(Boolean) }); onClose(); }}
            className="flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b828a0' }}>
            {dept ? 'Save Changes' : 'Add Department'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default function OrgStructureSection() {
  const [depts, setDepts] = useState<Department[]>(initialDepts);
  const [modal, setModal] = useState<'add' | 'edit' | null>(null);
  const [editing, setEditing] = useState<Department | null>(null);
  const [delTarget, setDelTarget] = useState<Department | null>(null);
  const [toast, setToast] = useState('');
  const [view, setView] = useState<'list' | 'chart'>('list');

  const showToast = (msg: string) => setToast(msg);

  const handleSave = (data: Omit<Department, 'id' | 'headCount'>) => {
    if (editing) {
      setDepts(ds => ds.map(d => d.id === editing.id ? { ...d, ...data } : d));
      showToast('Department updated successfully');
    } else {
      setDepts(ds => [...ds, { ...data, id: Date.now(), headCount: 0 }]);
      showToast('Department added successfully');
    }
  };

  return (
    <div>
      {toast && <ToastNotif message={toast} onDone={() => setToast('')} />}
      {(modal === 'add' || modal === 'edit') && (
        <DeptModal dept={editing} onClose={() => { setModal(null); setEditing(null); }} onSave={handleSave} />
      )}
      {delTarget && (
        <ConfirmDialog
          title="Delete Department"
          message={`Are you sure you want to delete "${delTarget.name}"? All linked positions and records will be affected.`}
          onConfirm={() => { setDepts(ds => ds.filter(d => d.id !== delTarget.id)); setDelTarget(null); showToast('Department deleted'); }}
          onCancel={() => setDelTarget(null)}
        />
      )}

      <SectionHeader icon="ri-organization-chart" title="Organization Structure" desc="Manage departments, positions, and org hierarchy"
        action={
          <div className="flex gap-2">
            <button onClick={() => setView(v => v === 'list' ? 'chart' : 'list')}
              className="flex items-center gap-2 px-3 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
              <div className="w-4 h-4 flex items-center justify-center"><i className={`${view === 'list' ? 'ri-bubble-chart-line' : 'ri-list-unordered'} text-sm`}></i></div>
              {view === 'list' ? 'Org Chart' : 'List View'}
            </button>
            <button onClick={() => { setModal('add'); setEditing(null); }}
              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 Department
            </button>
          </div>
        }
      />

      {view === 'chart' ? (
        <OrgChartView depts={depts} />
      ) : (
        <div className="space-y-3">
          {depts.map(dept => (
            <div key={dept.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" style={{ background: '#fdf0fb' }}>
                    <i className="ri-building-2-line text-lg" style={{ color: '#b828a0' }}></i>
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-bold text-gray-800">{dept.name}</p>
                      <span className="text-xs px-2 py-0.5 rounded-full bg-pink-100 font-mono font-semibold" style={{ color: '#b828a0' }}>{dept.code}</span>
                    </div>
                    <p className="text-xs text-gray-500 mt-0.5">Reports to: <span className="font-medium text-gray-700">{dept.parent}</span> · {dept.headCount} staff</p>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  <button onClick={() => { setEditing(dept); setModal('edit'); }}
                    className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer transition-colors">
                    <i className="ri-edit-2-line text-blue-500 text-sm"></i>
                  </button>
                  <button onClick={() => setDelTarget(dept)}
                    className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer transition-colors">
                    <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                  </button>
                </div>
              </div>
              <div className="mt-3 flex flex-wrap gap-1.5">
                {dept.positions.map(pos => (
                  <span key={pos} className="text-xs px-2.5 py-1 rounded-full bg-gray-100 text-gray-600">{pos}</span>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="mt-5 bg-white rounded-2xl border border-gray-100 shadow-sm p-4">
        <div className="flex items-center justify-between mb-3">
          <p className="text-sm font-bold text-gray-800">Bulk Import</p>
          <span className="text-xs text-gray-400">Supports CSV/Excel</span>
        </div>
        <div className="border-2 border-dashed border-gray-200 rounded-xl p-5 text-center hover:border-pink-300 transition-colors cursor-pointer">
          <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2" style={{ color: '#b828a0' }}><i className="ri-upload-cloud-2-line text-3xl"></i></div>
          <p className="text-sm font-medium text-gray-700">Drop your CSV/Excel file here</p>
          <p className="text-xs text-gray-400 mt-1">or <span className="underline" style={{ color: '#b828a0' }}>browse files</span></p>
        </div>
      </div>
    </div>
  );
}

function OrgChartView({ depts }: { depts: Department[] }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 overflow-x-auto">
      <p className="text-xs text-gray-400 mb-5 text-center">Organizational Hierarchy — Drag & drop to rearrange (visual preview)</p>
      <div className="flex flex-col items-center gap-4 min-w-max mx-auto">
        <div className="px-6 py-3 rounded-2xl text-white text-sm font-bold shadow-md" style={{ background: '#b828a0' }}>Executive Office</div>
        <div className="w-px h-6 bg-pink-300"></div>
        <div className="flex gap-6">
          {['Human Resources', 'Finance & Accounts', 'ICT & Systems', 'Program Management', 'Legal & Compliance', 'Communications'].map((d, i) => (
            <div key={i} className="flex flex-col items-center gap-2">
              <div className="w-px h-4 bg-pink-200"></div>
              <div className="px-4 py-2.5 rounded-xl border-2 text-xs font-semibold text-center bg-pink-50 text-gray-800 shadow-sm min-w-28" style={{ borderColor: '#b828a0' }}>{d}</div>
              {d === 'Program Management' && (
                <>
                  <div className="w-px h-4 bg-pink-200"></div>
                  <div className="px-3 py-2 rounded-xl border border-pink-200 text-xs text-center bg-white text-gray-600 min-w-28">Regional Coordination</div>
                </>
              )}
            </div>
          ))}
        </div>
      </div>
      <div className="flex justify-end mt-5">
        <button className="flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-2-line text-sm"></i></div>
          Export as PDF
        </button>
      </div>
    </div>
  );
}
