'use client';
import { useState } from 'react';
import { Candidate, statusColors, sourceColors, interviews, offers } from './recruitmentData';

interface Props {
  candidate: Candidate;
  onClose: () => void;
}

export default function CandidateDetailModal({ candidate, onClose }: Props) {
  const [activeTab, setActiveTab] = useState<'overview' | 'interviews' | 'offer' | 'notes'>('overview');
  const [note, setNote] = useState('');
  const [notes, setNotes] = useState<{ text: string; time: string; author: string }[]>([
    { text: 'Strong technical background. Performed well in initial phone screening.', time: '2026-03-20 10:15', author: 'HR Manager' },
  ]);

  const candidateInterviews = interviews.filter(i => i.candidateId === candidate.id);
  const candidateOffer = offers.find(o => o.candidateId === candidate.id);
  const totalPackage = candidateOffer ? candidateOffer.basicSalary + candidateOffer.housingAllowance + candidateOffer.transportAllowance + candidateOffer.otherAllowances : 0;

  const addNote = () => {
    if (!note.trim()) return;
    setNotes(prev => [...prev, { text: note, time: new Date().toISOString().slice(0, 16).replace('T', ' '), author: 'HR Manager' }]);
    setNote('');
  };

  const tabs = ['overview', 'interviews', 'offer', 'notes'] as const;

  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-hidden flex flex-col">
        <div className="flex items-start justify-between px-6 py-4 border-b border-gray-100">
          <div className="flex items-center gap-4">
            <div className="w-14 h-14 rounded-full flex items-center justify-center text-white text-lg font-bold flex-shrink-0" style={{ background: '#b828a0' }}>
              {candidate.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
            </div>
            <div>
              <h2 className="text-lg font-bold text-gray-800">{candidate.name}</h2>
              <p className="text-sm text-gray-500">{candidate.currentRole} {candidate.currentCompany ? `@ ${candidate.currentCompany}` : ''}</p>
              <div className="flex items-center gap-2 mt-1">
                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[candidate.status]}`}>{candidate.status}</span>
                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${sourceColors[candidate.source] || 'bg-gray-100 text-gray-600'}`}>{candidate.source}</span>
                {candidate.talentPool && (
                  <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-700">Talent Pool</span>
                )}
              </div>
            </div>
          </div>
          <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-600"></i>
          </button>
        </div>

        <div className="flex border-b border-gray-100">
          {tabs.map(t => (
            <button key={t} onClick={() => setActiveTab(t)} className={`px-5 py-3 text-sm font-medium capitalize transition-colors cursor-pointer ${activeTab === t ? 'text-pink-700 border-b-2 border-pink-600' : 'text-gray-400 hover:text-gray-600'}`}>{t}</button>
          ))}
        </div>

        <div className="flex-1 overflow-y-auto p-6">
          {activeTab === 'overview' && (
            <div className="space-y-5">
              <div className="grid grid-cols-3 gap-3">
                {[
                  { label: 'Email', value: candidate.email, icon: 'ri-mail-line' },
                  { label: 'Phone', value: candidate.phone, icon: 'ri-phone-line' },
                  { label: 'Location', value: candidate.location, icon: 'ri-map-pin-line' },
                  { label: 'Experience', value: `${candidate.yearsExperience} years`, icon: 'ri-briefcase-line' },
                  { label: 'Expected Salary', value: candidate.expectedSalary ? `KES ${candidate.expectedSalary.toLocaleString()}` : 'N/A', icon: 'ri-money-dollar-circle-line' },
                  { label: 'Applied Date', value: candidate.appliedDate, icon: 'ri-calendar-line' },
                ].map(item => (
                  <div key={item.label} className="bg-gray-50 rounded-xl p-3">
                    <div className="flex items-center gap-1.5 mb-1">
                      <div className="w-4 h-4 flex items-center justify-center"><i className={`${item.icon} text-gray-400 text-xs`}></i></div>
                      <span className="text-xs text-gray-400">{item.label}</span>
                    </div>
                    <div className="text-sm font-medium text-gray-700 truncate">{item.value}</div>
                  </div>
                ))}
              </div>
              <div>
                <h3 className="text-sm font-semibold text-gray-700 mb-2">Skills</h3>
                <div className="flex flex-wrap gap-2">
                  {candidate.skills.map(skill => (
                    <span key={skill} className="bg-purple-50 text-purple-700 border border-purple-100 px-3 py-1 rounded-full text-sm">{skill}</span>
                  ))}
                </div>
              </div>
              {candidate.education && (
                <div>
                  <h3 className="text-sm font-semibold text-gray-700 mb-1">Education</h3>
                  <p className="text-sm text-gray-600">{candidate.education}</p>
                </div>
              )}
              {candidate.referredBy && (
                <div className="bg-green-50 border border-green-100 rounded-xl p-3">
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 flex items-center justify-center"><i className="ri-user-heart-line text-green-600 text-sm"></i></div>
                    <span className="text-sm text-green-700"><strong>Referred by:</strong> {candidate.referredBy}</span>
                  </div>
                </div>
              )}
              {candidate.overallRating && (
                <div>
                  <h3 className="text-sm font-semibold text-gray-700 mb-2">Overall Interview Rating</h3>
                  <div className="flex items-center gap-2">
                    <div className="flex items-center gap-1">
                      {[1, 2, 3, 4, 5].map(n => (
                        <div key={n} className="w-5 h-5 flex items-center justify-center">
                          <i className={n <= Math.round(candidate.overallRating!) ? 'ri-star-fill text-yellow-400' : 'ri-star-line text-yellow-400'}></i>
                        </div>
                      ))}
                    </div>
                    <span className="text-lg font-bold text-gray-700">{candidate.overallRating}</span>
                    <span className="text-sm text-gray-400">/ 5.0</span>
                  </div>
                </div>
              )}
              <div className="flex gap-2 pt-2">
                <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-200 text-sm 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-line text-sm"></i></div>
                  Resume
                </button>
                <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-200 text-sm 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-mail-send-line text-sm"></i></div>
                  Send Email
                </button>
                <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
                  <div className="w-4 h-4 flex items-center justify-center"><i className="ri-calendar-check-line text-sm"></i></div>
                  Schedule Interview
                </button>
                {!candidate.talentPool && (
                  <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-purple-200 text-sm text-purple-700 hover:bg-purple-50 cursor-pointer whitespace-nowrap">
                    <div className="w-4 h-4 flex items-center justify-center"><i className="ri-bookmark-line text-sm"></i></div>
                    Add to Talent Pool
                  </button>
                )}
              </div>
            </div>
          )}

          {activeTab === 'interviews' && (
            <div className="space-y-3">
              {candidateInterviews.length === 0 && <div className="text-center py-8 text-gray-400 text-sm">No interviews scheduled yet</div>}
              {candidateInterviews.map(interview => (
                <div key={interview.id} className="border border-gray-100 rounded-xl p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <div className="font-semibold text-gray-800">{interview.round}</div>
                      <div className="text-sm text-gray-500">{interview.scheduledDate} at {interview.scheduledTime}</div>
                    </div>
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${interview.status === 'Completed' ? 'bg-green-100 text-green-700' : interview.status === 'Scheduled' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>{interview.status}</span>
                  </div>
                  <div className="flex flex-wrap gap-3 text-sm text-gray-500 mb-3">
                    <span className="flex items-center gap-1">
                      <div className="w-4 h-4 flex items-center justify-center"><i className="ri-video-line text-xs"></i></div>
                      {interview.mode}
                    </span>
                    {interview.meetingLink && (
                      <a href={interview.meetingLink} target="_blank" rel="noreferrer" className="text-blue-500 hover:underline text-xs cursor-pointer">{interview.meetingLink}</a>
                    )}
                  </div>
                  <div className="text-xs text-gray-500 mb-2">Interviewers: {interview.interviewers.join(', ')}</div>
                  {interview.feedback && (
                    <div className="bg-gray-50 rounded-xl p-3 mt-2">
                      <div className="text-xs font-semibold text-gray-600 mb-2">Interview Scorecard</div>
                      <div className="grid grid-cols-2 gap-2 mb-2">
                        {[
                          { label: 'Technical', score: interview.feedback.technical },
                          { label: 'Communication', score: interview.feedback.communication },
                          { label: 'Cultural Fit', score: interview.feedback.culturalFit },
                          { label: 'Overall', score: interview.feedback.overall },
                        ].map(item => (
                          <div key={item.label} className="flex items-center gap-2">
                            <span className="text-xs text-gray-500 w-24">{item.label}</span>
                            <div className="flex gap-0.5">
                              {[1, 2, 3, 4, 5].map(n => (
                                <div key={n} className="w-4 h-4 flex items-center justify-center">
                                  <i className={n <= item.score ? 'ri-star-fill text-yellow-400 text-xs' : 'ri-star-line text-yellow-400 text-xs'}></i>
                                </div>
                              ))}
                            </div>
                            <span className="text-xs font-semibold text-gray-600">{item.score}/5</span>
                          </div>
                        ))}
                      </div>
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-xs text-gray-500">Recommendation:</span>
                        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${interview.feedback.recommendation === 'Hire' ? 'bg-green-100 text-green-700' : interview.feedback.recommendation === 'No Hire' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'}`}>{interview.feedback.recommendation}</span>
                      </div>
                      <p className="text-xs text-gray-600 italic mt-1">"{interview.feedback.notes}"</p>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}

          {activeTab === 'offer' && (
            <div>
              {!candidateOffer ? (
                <div className="text-center py-8">
                  <div className="w-12 h-12 flex items-center justify-center rounded-full bg-gray-100 mx-auto mb-3">
                    <i className="ri-file-paper-2-line text-gray-400 text-xl"></i>
                  </div>
                  <p className="text-gray-500 text-sm mb-3">No offer generated yet</p>
                  <button className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Generate Offer Letter</button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center justify-between mb-1">
                    <h3 className="text-sm font-semibold text-gray-700">Offer Details</h3>
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${candidateOffer.status === 'Accepted' ? 'bg-green-100 text-green-700' : candidateOffer.status === 'Extended' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>{candidateOffer.status}</span>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    {[
                      { label: 'Basic Salary', value: `KES ${candidateOffer.basicSalary.toLocaleString()}` },
                      { label: 'Housing Allowance', value: `KES ${candidateOffer.housingAllowance.toLocaleString()}` },
                      { label: 'Transport Allowance', value: `KES ${candidateOffer.transportAllowance.toLocaleString()}` },
                      { label: 'Other Allowances', value: `KES ${candidateOffer.otherAllowances.toLocaleString()}` },
                    ].map(item => (
                      <div key={item.label} className="bg-gray-50 rounded-xl p-3">
                        <div className="text-xs text-gray-400">{item.label}</div>
                        <div className="font-semibold text-gray-800 text-sm">{item.value}</div>
                      </div>
                    ))}
                  </div>
                  <div className="bg-purple-50 border border-purple-100 rounded-xl p-4 flex items-center justify-between">
                    <div>
                      <div className="text-xs text-purple-500 mb-0.5">Total Monthly Package</div>
                      <div className="text-2xl font-bold text-purple-700">KES {totalPackage.toLocaleString()}</div>
                    </div>
                    <div className="text-right">
                      <div className="text-xs text-gray-500">Start Date</div>
                      <div className="font-semibold text-gray-700 text-sm">{candidateOffer.startDate}</div>
                      <div className="text-xs text-gray-400 mt-1">Expiry: {candidateOffer.expiryDate}</div>
                    </div>
                  </div>
                  <div className="grid grid-cols-3 gap-3">
                    <div className="bg-gray-50 rounded-xl p-3 text-center">
                      <div className="text-xs text-gray-400 mb-1">Insurance</div>
                      <div className={`text-sm font-semibold ${candidateOffer.insurance ? 'text-green-600' : 'text-gray-400'}`}>{candidateOffer.insurance ? 'Included' : 'Not Included'}</div>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-3 text-center">
                      <div className="text-xs text-gray-400 mb-1">Bonus</div>
                      <div className="text-sm font-semibold text-gray-700">{candidateOffer.bonusPercent}% of Basic</div>
                    </div>
                    <div className="bg-gray-50 rounded-xl p-3 text-center">
                      <div className="text-xs text-gray-400 mb-1">Annual Leave</div>
                      <div className="text-sm font-semibold text-gray-700">{candidateOffer.annualLeave} days</div>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-200 text-sm 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-file-download-line text-sm"></i></div>
                      Download Offer Letter
                    </button>
                    {candidateOffer.status === 'Extended' && (
                      <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
                        <div className="w-4 h-4 flex items-center justify-center"><i className="ri-mail-send-line text-sm"></i></div>
                        Resend Offer
                      </button>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'notes' && (
            <div className="space-y-4">
              <div className="space-y-3">
                {notes.map((n, i) => (
                  <div key={i} className="bg-gray-50 rounded-xl p-3">
                    <p className="text-sm text-gray-700">{n.text}</p>
                    <div className="text-xs text-gray-400 mt-1">{n.author} · {n.time}</div>
                  </div>
                ))}
              </div>
              <div className="border-t border-gray-100 pt-4">
                <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Add a note about this candidate..." rows={3} maxLength={500} className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300 resize-none" />
                <div className="flex justify-between items-center mt-2">
                  <span className="text-xs text-gray-400">{note.length}/500</span>
                  <button onClick={addNote} disabled={!note.trim()} className="px-4 py-1.5 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap disabled:opacity-40" style={{ background: '#b828a0' }}>Add Note</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
