'use client';
import { useState } from 'react';
import { candidates, statusColors, sourceColors, pipelineStages, CandidateStatus, Candidate } from './recruitmentData';

interface Props {
  onViewCandidate: (c: Candidate) => void;
}

const stages: CandidateStatus[] = ['New Application', 'Screening', 'Shortlisted', 'Interview Scheduled', 'Technical Assessment', 'Final Interview', 'Offer Extended', 'Offer Accepted', 'Hired', 'Rejected', 'Withdrawn'];

export default function CandidatesTab({ onViewCandidate }: Props) {
  const [view, setView] = useState<'list' | 'pipeline'>('list');
  const [filterStatus, setFilterStatus] = useState('All');
  const [filterSource, setFilterSource] = useState('All');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<string[]>([]);

  const filtered = candidates.filter(c => {
    const matchStatus = filterStatus === 'All' || c.status === filterStatus;
    const matchSource = filterSource === 'All' || c.source === filterSource;
    const matchSearch = c.name.toLowerCase().includes(search.toLowerCase()) || c.email.toLowerCase().includes(search.toLowerCase()) || c.skills.some(s => s.toLowerCase().includes(search.toLowerCase()));
    return matchStatus && matchSource && matchSearch;
  });

  const toggleSelect = (id: string) => {
    setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const pipelineData = pipelineStages.map(stage => ({
    stage,
    count: candidates.filter(c => c.status === stage).length,
    items: candidates.filter(c => c.status === stage),
  }));

  return (
    <div>
      <div className="flex flex-wrap items-center gap-3 mb-5">
        <div className="flex-1 min-w-64 relative">
          <div className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
            <i className="ri-search-line text-gray-400 text-sm"></i>
          </div>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search by name, email, skills..." className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" />
        </div>
        <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300 pr-8">
          <option value="All">All Statuses</option>
          {stages.map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        <select value={filterSource} onChange={e => setFilterSource(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300 pr-8">
          <option value="All">All Sources</option>
          {['LinkedIn', 'Indeed', 'Career Site', 'Referral', 'Agency', 'Internal'].map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        <div className="flex items-center border border-gray-200 rounded-lg overflow-hidden">
          <button onClick={() => setView('list')} className={`px-3 py-2 text-sm cursor-pointer ${view === 'list' ? 'text-white' : 'text-gray-500 hover:bg-gray-50'}`} style={view === 'list' ? { background: '#b828a0' } : {}}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-list-check text-sm"></i></div>
          </button>
          <button onClick={() => setView('pipeline')} className={`px-3 py-2 text-sm cursor-pointer ${view === 'pipeline' ? 'text-white' : 'text-gray-500 hover:bg-gray-50'}`} style={view === 'pipeline' ? { background: '#b828a0' } : {}}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-kanban-view text-sm"></i></div>
          </button>
        </div>
        {selected.length > 0 && (
          <div className="flex items-center gap-2 bg-purple-50 border border-purple-200 rounded-lg px-3 py-2">
            <span className="text-xs text-purple-700 font-medium">{selected.length} selected</span>
            <select className="border-0 bg-transparent text-xs text-purple-700 focus:outline-none pr-4">
              <option>Move to Stage...</option>
              {stages.map(s => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
        )}
      </div>

      {view === 'pipeline' ? (
        <div className="overflow-x-auto">
          <div className="flex gap-3 min-w-max pb-3">
            {pipelineData.map(({ stage, count, items }) => (
              <div key={stage} className="w-52 flex-shrink-0">
                <div className="flex items-center justify-between mb-2">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[stage]}`}>{stage}</span>
                  <span className="text-xs text-gray-400 font-semibold">{count}</span>
                </div>
                <div className="space-y-2">
                  {items.map(c => (
                    <div key={c.id} onClick={() => onViewCandidate(c)} className="bg-white border border-gray-100 rounded-xl p-3 shadow-sm cursor-pointer hover:shadow-md hover:border-pink-200 transition-all">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: '#b828a0' }}>
                          {c.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                        </div>
                        <div className="min-w-0">
                          <div className="text-xs font-semibold text-gray-800 truncate">{c.name}</div>
                          <div className="text-xs text-gray-400 truncate">{c.currentRole}</div>
                        </div>
                      </div>
                      <div className="text-xs text-gray-500 truncate">{c.jobTitle}</div>
                      {c.overallRating && (
                        <div className="flex items-center gap-1 mt-1">
                          <div className="w-3 h-3 flex items-center justify-center"><i className="ri-star-fill text-yellow-400 text-xs"></i></div>
                          <span className="text-xs text-gray-600">{c.overallRating}</span>
                        </div>
                      )}
                    </div>
                  ))}
                  {items.length === 0 && <div className="text-center py-4 text-xs text-gray-400">No candidates</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                <th className="px-4 py-3 text-left">
                  <input type="checkbox" className="rounded" />
                </th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Candidate</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Applied For</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Source</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Exp</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Skills</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Status</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Rating</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Applied</th>
                <th className="text-left px-4 py-3 text-gray-600 font-semibold">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((c) => (
                <tr key={c.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3">
                    <input type="checkbox" className="rounded" checked={selected.includes(c.id)} onChange={() => toggleSelect(c.id)} />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: '#b828a0' }}>
                        {c.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                      </div>
                      <div>
                        <div className="font-medium text-gray-800">{c.name}</div>
                        <div className="text-xs text-gray-400">{c.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm text-gray-700">{c.jobTitle}</div>
                    <div className="text-xs text-gray-400">{c.currentCompany}</div>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${sourceColors[c.source] || 'bg-gray-100 text-gray-600'}`}>{c.source}</span>
                  </td>
                  <td className="px-4 py-3 text-gray-600 text-xs">{c.yearsExperience}yr{c.yearsExperience !== 1 ? 's' : ''}</td>
                  <td className="px-4 py-3">
                    <div className="flex flex-wrap gap-1">
                      {c.skills.slice(0, 2).map(s => (
                        <span key={s} className="bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded text-xs">{s}</span>
                      ))}
                      {c.skills.length > 2 && <span className="text-xs text-gray-400">+{c.skills.length - 2}</span>}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[c.status]}`}>{c.status}</span>
                  </td>
                  <td className="px-4 py-3">
                    {c.overallRating ? (
                      <div className="flex items-center gap-1">
                        <div className="w-3 h-3 flex items-center justify-center"><i className="ri-star-fill text-yellow-400 text-xs"></i></div>
                        <span className="text-sm font-medium text-gray-700">{c.overallRating}</span>
                      </div>
                    ) : <span className="text-xs text-gray-300">—</span>}
                  </td>
                  <td className="px-4 py-3 text-xs text-gray-400">{c.appliedDate}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button onClick={() => onViewCandidate(c)} className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-blue-50 text-blue-600 cursor-pointer" title="View Profile">
                        <i className="ri-user-line text-sm"></i>
                      </button>
                      {c.talentPool && (
                        <div className="w-5 h-5 flex items-center justify-center" title="In Talent Pool">
                          <i className="ri-bookmark-fill text-purple-500 text-sm"></i>
                        </div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && <div className="text-center py-10 text-gray-400 text-sm">No candidates found</div>}
        </div>
      )}
    </div>
  );
}
