'use client';
import { useState } from 'react';
import { usePerformanceStore } from '../../../lib/performanceStore';

const BRAND = '#B22698';

interface StaffReviewItem {
  id: string;
  type: 'workplan' | 'kpi' | 'ipi' | 'quarterly';
  title: string;
  detail: string;
  progress?: number;
  status?: string;
}

interface Props {
  employee: { id: string; name: string; role: string; dept: string };
  onClose: () => void;
}

const MOCK_PERFORMANCE: Record<string, StaffReviewItem[]> = {
  'Peter Otieno': [
    { id: 'WP1', type: 'workplan', title: 'Deploy new training portal', detail: 'Target: Portal live by Q2', progress: 30, status: 'In Progress' },
    { id: 'K1', type: 'kpi', title: 'Portal Uptime KPI', detail: 'Target: 99.5% uptime', progress: 40, status: 'Active' },
    { id: 'IPI1', type: 'ipi', title: 'User onboarding completion rate', detail: 'Baseline: 50% → Target: 90%', progress: 55 },
    { id: 'QT1', type: 'quarterly', title: 'Complete portal MVP by Q2', detail: 'KPI: Portal live with 80%+ user adoption', progress: 30, status: 'In Progress' },
  ],
  'Alice Odhiambo': [
    { id: 'WP2', type: 'workplan', title: 'Migrate database to cloud', detail: 'Target: Cloud migration 100%', progress: 70, status: 'In Progress' },
    { id: 'K2', type: 'kpi', title: 'Database migration speed', detail: 'Target: 100% migration', progress: 70, status: 'Active' },
    { id: 'IPI2', type: 'ipi', title: 'Zero downtime during migration', detail: 'Target: 0 minutes downtime', progress: 80 },
    { id: 'QT2', type: 'quarterly', title: 'Full cloud migration by Q2', detail: 'KPI: All databases on cloud', progress: 70, status: 'In Progress' },
  ],
  'Brian Omondi': [
    { id: 'WP3', type: 'workplan', title: 'Network security audit', detail: 'Target: All vulnerabilities patched', progress: 90, status: 'Completed' },
    { id: 'K3', type: 'kpi', title: 'Security patches applied', detail: 'Target: 100% patches', progress: 95, status: 'Active' },
    { id: 'IPI3', type: 'ipi', title: 'Security incident response time', detail: 'Target: < 2 hours response', progress: 90 },
    { id: 'QT3', type: 'quarterly', title: 'Zero security incidents Q2', detail: 'KPI: No P1/P2 security incidents', progress: 90, status: 'Completed' },
  ],
};

const TYPE_LABELS: Record<string, string> = {
  workplan: 'Work Plan',
  kpi: 'KPI',
  ipi: 'IPI',
  quarterly: 'Quarterly Target',
};

const TYPE_ICONS: Record<string, string> = {
  workplan: 'ri-file-list-3-line',
  kpi: 'ri-bar-chart-line',
  ipi: 'ri-line-chart-line',
  quarterly: 'ri-calendar-check-line',
};

const TYPE_COLORS: Record<string, string> = {
  workplan: '#2563eb',
  kpi: '#b828a0',
  ipi: '#059669',
  quarterly: '#d97706',
};

export default function StaffReviewModal({ employee, onClose }: Props) {
  const { addComment, getCommentsFor } = usePerformanceStore();
  const [commentModal, setCommentModal] = useState<StaffReviewItem | null>(null);
  const [comment, setComment] = useState('');
  const [toast, setToast] = useState('');
  const [filterType, setFilterType] = useState<'all' | 'workplan' | 'kpi' | 'ipi' | 'quarterly'>('all');

  const items: StaffReviewItem[] = MOCK_PERFORMANCE[employee.name] || [
    { id: 'WP-DEF1', type: 'workplan', title: 'Departmental work plan', detail: 'Progress as per targets', progress: 50, status: 'In Progress' },
    { id: 'K-DEF1', type: 'kpi', title: 'Department KPI', detail: 'Monthly tracking', progress: 60, status: 'Active' },
    { id: 'IPI-DEF1', type: 'ipi', title: 'Performance indicator', detail: 'Linked to work plan', progress: 55 },
    { id: 'QT-DEF1', type: 'quarterly', title: 'Quarterly target', detail: 'Q2 deliverable', progress: 45, status: 'In Progress' },
  ];

  const existingComments = getCommentsFor(employee.id);
  const filteredItems = filterType === 'all' ? items : items.filter(i => i.type === filterType);

  const handleSendComment = () => {
    if (!commentModal || !comment.trim()) return;
    addComment({
      employeeId: employee.id,
      itemType: commentModal.type,
      itemId: commentModal.id,
      itemTitle: commentModal.title,
      commentBy: employee.dept + ' HOD',
      commentByRole: 'HOD',
      comment: comment.trim(),
    });
    setToast(`Comment sent to ${employee.name} on ${TYPE_LABELS[commentModal.type]}: "${commentModal.title}"`);
    setTimeout(() => setToast(''), 4000);
    setCommentModal(null);
    setComment('');
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
          <div>
            <h3 className="font-bold text-white">Review: {employee.name}</h3>
            <p className="text-pink-200 text-xs">{employee.role} · {employee.dept}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-white text-xl"></i>
          </button>
        </div>

        {toast && (
          <div className="mx-6 mt-4 px-4 py-3 rounded-xl text-white text-sm font-medium flex items-center gap-2" style={{ background: '#059669' }}>
            <i className="ri-checkbox-circle-line"></i> {toast}
          </div>
        )}

        <div className="p-6 space-y-5">
          <div className="flex gap-2 flex-wrap">
            {(['all', 'workplan', 'kpi', 'ipi', 'quarterly'] as const).map(t => (
              <button key={t} onClick={() => setFilterType(t)}
                className="px-3 py-1.5 rounded-full text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
                style={filterType === t ? { background: BRAND, color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
                {t === 'all' ? 'All' : TYPE_LABELS[t]}
              </button>
            ))}
          </div>

          {existingComments.length > 0 && (
            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <p className="text-xs font-semibold text-amber-700 mb-2">Your Previous Comments ({existingComments.length})</p>
              <div className="space-y-2 max-h-32 overflow-y-auto">
                {existingComments.map(c => (
                  <div key={c.id} className="flex items-start gap-2 text-xs text-gray-700">
                    <span className="px-2 py-0.5 rounded-full font-medium bg-amber-100 text-amber-700 whitespace-nowrap">{TYPE_LABELS[c.itemType]}</span>
                    <span className="text-gray-500">{c.createdAt}:</span>
                    <span className="flex-1">{c.comment}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="space-y-3">
            {filteredItems.map(item => {
              const itemComments = existingComments.filter(c => c.itemId === item.id);
              return (
                <div key={item.id} className="bg-white border border-gray-100 rounded-xl p-4 shadow-sm">
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex items-start gap-3 flex-1">
                      <div className="w-8 h-8 flex items-center justify-center rounded-lg flex-shrink-0" style={{ background: TYPE_COLORS[item.type] + '15' }}>
                        <i className={`${TYPE_ICONS[item.type]} text-sm`} style={{ color: TYPE_COLORS[item.type] }}></i>
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ background: TYPE_COLORS[item.type] + '15', color: TYPE_COLORS[item.type] }}>
                            {TYPE_LABELS[item.type]}
                          </span>
                          {item.status && (
                            <span className="text-xs px-2 py-0.5 rounded-full font-medium bg-gray-100 text-gray-600">{item.status}</span>
                          )}
                        </div>
                        <p className="font-semibold text-gray-800 text-sm">{item.title}</p>
                        <p className="text-xs text-gray-500 mt-0.5">{item.detail}</p>
                        {item.progress !== undefined && (
                          <div className="flex items-center gap-2 mt-2">
                            <div className="flex-1 bg-gray-100 rounded-full h-1.5 max-w-32">
                              <div className="h-1.5 rounded-full" style={{ width: `${item.progress}%`, background: TYPE_COLORS[item.type] }}></div>
                            </div>
                            <span className="text-xs font-bold text-gray-600">{item.progress}%</span>
                          </div>
                        )}
                        {itemComments.length > 0 && (
                          <div className="mt-2 bg-green-50 border border-green-200 rounded-lg p-2">
                            <p className="text-xs text-green-700 font-semibold mb-1">Your comment:</p>
                            <p className="text-xs text-green-800">{itemComments[0].comment}</p>
                          </div>
                        )}
                      </div>
                    </div>
                    <button
                      onClick={() => { setCommentModal(item); setComment(''); }}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border transition-all hover:bg-pink-50"
                      style={{ borderColor: BRAND, color: BRAND }}>
                      <i className="ri-chat-3-line"></i>
                      {itemComments.length > 0 ? 'Edit Comment' : 'Add Comment'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="px-6 py-4 border-t border-gray-100">
          <button onClick={onClose} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
            Close
          </button>
        </div>
      </div>

      {commentModal && (
        <div className="fixed inset-0 bg-black/60 z-[60] flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-9 h-9 flex items-center justify-center rounded-xl" style={{ background: BRAND }}>
                <i className="ri-chat-3-line text-white text-base"></i>
              </div>
              <div>
                <h4 className="font-bold text-gray-800">Add Review Comment</h4>
                <p className="text-xs text-gray-500">{TYPE_LABELS[commentModal.type]}: {commentModal.title}</p>
              </div>
            </div>
            <div className="bg-gray-50 rounded-xl p-3 mb-4">
              <p className="text-xs text-gray-500">To: <strong>{employee.name}</strong></p>
              <p className="text-xs text-gray-400 mt-1">{commentModal.detail}</p>
            </div>
            <div className="mb-4">
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Your Comment / Feedback *</label>
              <textarea value={comment} onChange={e => setComment(e.target.value)} rows={4} maxLength={500}
                placeholder="Provide specific feedback and areas for improvement..."
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none resize-none" />
              <p className="text-xs text-gray-400 text-right mt-1">{comment.length}/500</p>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setCommentModal(null)}
                className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleSendComment} disabled={!comment.trim()}
                className="flex-1 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
                style={{ background: BRAND }}>
                Send to {employee.name}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}