import { CheckCircle, MessageCircle, Copy, Edit, Trash2, ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
import { WAInvitation, Leader, Aspect, Question } from '../../types';

interface WAInvitationTableProps {
  paginatedInvitations: WAInvitation[];
  leaders: Leader[];
  aspects: Aspect[];
  questions: Question[];
  onSendToWhatsApp: (invite: WAInvitation) => void;
  onCopyLink: (invite: WAInvitation) => void;
  onEdit: (invite: WAInvitation) => void;
  onDelete: (invite: WAInvitation) => void;
  calculateAspectProgress: (invite: WAInvitation, leaders: Leader[]) => Record<number, number>;
  sortOrder: 'asc' | 'desc' | 'none';
  onToggleSort: () => void;
}

export default function WAInvitationTable({
  paginatedInvitations,
  leaders,
  aspects,
  questions,
  onSendToWhatsApp,
  onCopyLink,
  onEdit,
  onDelete,
  calculateAspectProgress,
  sortOrder,
  onToggleSort
}: WAInvitationTableProps) {
  return (
    <div className="space-y-4">
      {/* Tampilan Desktop (Tabel) */}
      <div className="hidden md:block bg-white dark:bg-slate-800 rounded-2xl border border-slate-100 dark:border-slate-700/50 shadow-xs overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-100 dark:border-slate-800 text-[9px] font-bold text-slate-400 uppercase tracking-wider">
                <th className="py-3 px-4 select-none">
                  <button
                    type="button"
                    onClick={onToggleSort}
                    className="flex items-center gap-1 hover:text-slate-600 dark:hover:text-slate-300 transition-colors bg-transparent border-0 p-0 font-bold uppercase tracking-wider text-[9px] cursor-pointer focus:outline-none"
                    title="Urutkan berdasarkan nama alfabet"
                  >
                    <span>Target Penerima</span>
                    {sortOrder === 'asc' && <ArrowUp className="h-3 w-3 text-blue-500" />}
                    {sortOrder === 'desc' && <ArrowDown className="h-3 w-3 text-blue-500" />}
                    {sortOrder === 'none' && <ArrowUpDown className="h-3 w-3 text-slate-300 dark:text-slate-600 opacity-60" />}
                  </button>
                </th>
                <th className="py-3 px-3">No. WhatsApp</th>
                <th className="py-3 px-2 text-center">Status</th>
                <th className="py-3 px-3">Unit / Prodi</th>
                {aspects.map((asp, idx) => (
                  <th key={asp.id} className="py-3 px-2 text-center" title={asp.title}>
                    A{idx + 1}: {asp.title.split(' ').pop()}
                  </th>
                ))}
                <th className="py-3 px-3 text-center">Status Kirim</th>
                <th className="py-3 px-3 text-center">Partisipasi</th>
                <th className="py-3 px-3 text-right">Tindakan</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
              {paginatedInvitations.map((invite) => {
                const hasBeenSent = invite.sentCount > 0;
                const progress = calculateAspectProgress(invite, leaders);
                
                return (
                  <tr key={invite.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition">
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-2">
                        <div className={`h-7 w-7 rounded-full flex items-center justify-center text-[10px] font-bold font-mono ${
                          invite.role === 'Dosen'
                            ? 'bg-blue-50 text-blue-600 dark:bg-blue-950/20 dark:text-blue-400'
                            : 'bg-purple-50 text-purple-600 dark:bg-purple-950/20 dark:text-purple-400'
                        }`}>
                          {invite.name.slice(0, 2).toUpperCase()}
                        </div>
                        <div>
                          <span className="font-bold text-slate-800 dark:text-white block text-xs">{invite.name}</span>
                          <span className="text-[8px] text-slate-400 block font-mono">ID: {invite.id}</span>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-3">
                      <span className="text-xs text-slate-700 dark:text-slate-300 font-medium font-mono">
                        +{invite.phone}
                      </span>
                    </td>
                    <td className="py-4 px-2 text-center">
                      <span className={`inline-block px-1.5 py-0.5 rounded-full text-[8px] font-bold uppercase ${
                        invite.role === 'Dosen'
                          ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                          : 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400'
                      }`}>
                        {invite.role === 'Dosen' ? 'Dosen' : 'Tendik'}
                      </span>
                    </td>
                    <td className="py-4 px-3">
                      <span className="text-xs text-slate-600 dark:text-slate-300 font-medium whitespace-nowrap overflow-hidden text-ellipsis max-w-[120px] block" title={invite.unit}>
                        {invite.unit}
                      </span>
                    </td>
                    
                    {/* Aspect progress columns */}
                    {aspects.map((asp) => {
                      const count = progress[asp.id] || 0;
                      const totalQuestionsForAspect = questions.filter(q => q.aspectId === asp.id).length;
                      const totalPerAspect = leaders.length * totalQuestionsForAspect;
                      const isDone = count === totalPerAspect;
                      const hasProgress = count > 0;
                      return (
                        <td key={asp.id} className="py-4 px-2 text-center font-mono text-xs font-bold">
                          <span className={
                            isDone
                              ? "text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/20 px-1 py-0.5 rounded"
                              : hasProgress
                                ? "text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/20 px-1 py-0.5 rounded"
                                : "text-slate-300 dark:text-slate-600"
                          }>
                            {count}/{totalPerAspect}
                          </span>
                        </td>
                      );
                    })}

                    <td className="py-4 px-3 text-center">
                      <div className="flex justify-center">
                        {hasBeenSent ? (
                          <div className="flex flex-col items-center">
                            <span className="bg-emerald-100 text-emerald-800 dark:bg-emerald-950/20 dark:text-emerald-400 text-[10px] font-bold px-2 py-0.5 rounded-lg inline-flex items-center gap-1.5 shadow-3xs">
                              <CheckCircle className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
                              Sudah Kirim ({invite.sentCount}x)
                            </span>
                            {invite.lastSentAt && (
                              <span className="text-[8px] text-slate-400 block mt-1 font-mono">
                                {new Date(invite.lastSentAt).toLocaleDateString('id-ID', { day: 'numeric', month: 'short' })}
                              </span>
                            )}
                          </div>
                        ) : (
                          <span className="bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400 text-[10px] font-extrabold px-2 py-0.5 rounded-lg uppercase tracking-wider">
                            Belum Kirim
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="py-4 px-3 text-center">
                      <div className="flex justify-center">
                        {invite.isCompleted ? (
                          <span className="bg-emerald-50 text-emerald-700 dark:bg-emerald-900/35 dark:text-emerald-400 text-[10px] font-bold px-2 py-0.5 rounded-lg inline-flex items-center gap-1 border border-emerald-100 dark:border-emerald-900/40 shadow-3xs">
                            <span className="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                            Selesai
                          </span>
                        ) : (
                          <span className="bg-amber-50 text-amber-700 dark:bg-amber-900/35 dark:text-amber-400 text-[10px] font-bold px-2 py-0.5 rounded-lg inline-flex items-center gap-1 border border-amber-100 dark:border-amber-900/40 shadow-3xs">
                            <span className="h-1.5 w-1.5 rounded-full bg-amber-500 animate-pulse"></span>
                            Belum Selesai
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="py-4 px-3 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => onSendToWhatsApp(invite)}
                          className="px-2 py-1 bg-emerald-600 hover:bg-emerald-700 text-white dark:bg-emerald-500 dark:hover:bg-emerald-600 rounded-lg text-3xs font-bold leading-none inline-flex items-center gap-1 transition shadow-3xs cursor-pointer"
                          title={invite.isCompleted ? "Kirim ulang konfirmasi selesai" : "Kirim link/ingatkan pengisian"}
                        >
                          <MessageCircle className="h-3 w-3 fill-white" />
                          <span>Kirim WA</span>
                        </button>

                        <button
                          onClick={() => onCopyLink(invite)}
                          className="p-1 px-1.5 border border-slate-200 dark:border-slate-700 hover:border-slate-300 text-slate-500 hover:text-blue-600 dark:text-slate-300 rounded-lg transition cursor-pointer bg-white dark:bg-slate-800"
                          title="Salin Tautan Pribadi Responden"
                        >
                          <Copy className="h-3 w-3" />
                        </button>

                        <button
                          onClick={() => onEdit(invite)}
                          className="p-1 px-1.5 border border-slate-200 dark:border-slate-700 hover:border-slate-300 text-slate-500 hover:text-amber-600 dark:text-slate-300 rounded-lg transition cursor-pointer bg-white dark:bg-slate-800"
                          title="Ubah profil"
                        >
                          <Edit className="h-3 w-3" />
                        </button>

                        <button
                          onClick={() => onDelete(invite)}
                          className="p-1 px-1.5 border border-slate-200 dark:border-slate-700 hover:border-slate-300 text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/20 rounded-lg transition cursor-pointer bg-white dark:bg-slate-800"
                          title="Hapus peserta"
                        >
                          <Trash2 className="h-3 w-3" />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Tampilan Mobile (Daftar Kartu yang Dioptimalkan) */}
      <div className="block md:hidden space-y-4">
        {paginatedInvitations.map((invite) => {
          const hasBeenSent = invite.sentCount > 0;
          const progress = calculateAspectProgress(invite, leaders);

          return (
            <div 
              key={invite.id} 
              className="bg-white dark:bg-slate-800 p-4.5 rounded-2xl border border-slate-100 dark:border-slate-700/50 shadow-xs space-y-3.5 transition duration-200 active:scale-[0.99] active:bg-slate-50/50 dark:active:bg-slate-900/10"
            >
              {/* Baris Pertama: Nama, Peran, & Status Partisipasi */}
              <div className="flex items-start justify-between gap-2">
                <div className="flex items-center gap-2.5">
                  <div className={`h-8 w-8 rounded-full flex items-center justify-center text-xs font-black font-mono shrink-0 ${
                    invite.role === 'Dosen'
                      ? 'bg-blue-50 text-blue-600 dark:bg-blue-950/20 dark:text-blue-400'
                      : 'bg-purple-50 text-purple-600 dark:bg-purple-950/20 dark:text-purple-400'
                  }`}>
                    {invite.name.slice(0, 2).toUpperCase()}
                  </div>
                  <div>
                    <h4 className="font-extrabold text-slate-800 dark:text-white text-xs leading-snug">{invite.name}</h4>
                    <div className="flex items-center gap-1.5 mt-0.5">
                      <span className={`inline-block px-1.5 py-0.5 rounded-full text-[8px] font-bold uppercase tracking-wider ${
                        invite.role === 'Dosen'
                          ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                          : 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400'
                      }`}>
                        {invite.role === 'Dosen' ? 'Dosen' : 'Tendik'}
                      </span>
                      <span className="text-[8px] text-slate-400 font-mono">ID: {invite.id}</span>
                    </div>
                  </div>
                </div>

                <div className="shrink-0">
                  {invite.isCompleted ? (
                    <span className="bg-emerald-50 text-emerald-700 dark:bg-emerald-900/35 dark:text-emerald-400 text-[10px] font-bold px-2 py-0.5 rounded-lg inline-flex items-center gap-1 border border-emerald-100 dark:border-emerald-900/40 shadow-3xs">
                      <span className="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                      Selesai
                    </span>
                  ) : (
                    <span className="bg-amber-50 text-amber-700 dark:bg-amber-900/35 dark:text-amber-400 text-[10px] font-bold px-2 py-0.5 rounded-lg inline-flex items-center gap-1 border border-amber-100 dark:border-amber-900/40 shadow-3xs">
                      <span className="h-1.5 w-1.5 rounded-full bg-amber-500 animate-pulse"></span>
                      Proses
                    </span>
                  )}
                </div>
              </div>

              {/* Baris Kedua: Nomor WA & Unit/Prodi */}
              <div className="grid grid-cols-2 gap-3 text-2xs pt-1.5 border-t border-slate-100/60 dark:border-slate-700/30">
                <div>
                  <span className="text-slate-400 block text-[9px]">No. WhatsApp</span>
                  <span className="font-bold text-slate-700 dark:text-slate-300 font-mono text-[11px]">+{invite.phone}</span>
                </div>
                <div>
                  <span className="text-slate-400 block text-[9px]">Unit / Program Studi</span>
                  <span className="font-bold text-slate-700 dark:text-slate-300 block truncate" title={invite.unit}>{invite.unit}</span>
                </div>
              </div>

              {/* Baris Ketiga: Ringkasan Progres Kuesioner (Mini Grid Aspek A1-A6) */}
              <div className="bg-slate-50 dark:bg-slate-900/50 p-2.5 rounded-xl border border-slate-100/70 dark:border-slate-800/80">
                <span className="text-[8px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest block mb-2">Progres Pengisian Aspek</span>
                <div className="grid grid-cols-3 gap-1.5 font-mono text-3xs font-bold text-center">
                  {aspects.map((asp, idx) => {
                    const count = progress[asp.id] || 0;
                    const totalQuestionsForAspect = questions.filter(q => q.aspectId === asp.id).length;
                    const totalPerAspect = leaders.length * totalQuestionsForAspect;
                    const isDone = count === totalPerAspect;
                    const hasProgress = count > 0;
                    return (
                      <div key={asp.id} className={`p-1 rounded border flex flex-col justify-center ${
                        isDone 
                          ? "bg-emerald-50/70 border-emerald-100/60 dark:bg-emerald-950/20 dark:border-emerald-900/30 text-emerald-600 dark:text-emerald-400"
                          : hasProgress
                            ? "bg-blue-50/70 border-blue-100/60 dark:bg-blue-950/20 dark:border-blue-900/30 text-blue-600 dark:text-blue-400"
                            : "bg-slate-100/50 border-slate-200/50 dark:bg-slate-800/40 dark:border-slate-700/40 text-slate-300 dark:text-slate-600"
                      }`}>
                        <span className="text-[7px] text-slate-400 dark:text-slate-500 font-sans block">A{idx + 1}</span>
                        <span className="text-[9px] mt-0.5">{count}/{totalPerAspect}</span>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Baris Keempat: Status Kirim & Aksi Utama Kirim WA */}
              <div className="flex items-center justify-between gap-3 pt-3 border-t border-slate-100 dark:border-slate-700/50">
                <div className="text-left shrink-0">
                  {hasBeenSent ? (
                    <div>
                      <span className="text-[10px] font-bold text-emerald-600 dark:text-emerald-400 flex items-center gap-1">
                        <CheckCircle className="h-3 w-3 text-emerald-500" />
                        Sudah Kirim ({invite.sentCount}x)
                      </span>
                      {invite.lastSentAt && (
                        <span className="text-[8px] text-slate-400 block mt-0.5 font-mono">
                          {new Date(invite.lastSentAt).toLocaleDateString('id-ID', { day: 'numeric', month: 'short' })}
                        </span>
                      )}
                    </div>
                  ) : (
                    <span className="text-[9px] font-extrabold text-slate-400 dark:text-slate-500 uppercase tracking-wider bg-slate-100 dark:bg-slate-900 px-1.5 py-0.5 rounded-md">
                      Belum Kirim
                    </span>
                  )}
                </div>

                <div className="flex items-center gap-1.5">
                  {/* Tindakan Tambahan: Copy, Edit, Delete */}
                  <div className="flex items-center gap-1 border-r border-slate-200 dark:border-slate-700 pr-1.5">
                    <button
                      onClick={() => onCopyLink(invite)}
                      className="p-2 text-slate-500 hover:text-blue-600 dark:text-slate-300 rounded-lg transition active:bg-slate-100 dark:active:bg-slate-900 cursor-pointer"
                      title="Salin Tautan Pribadi Responden"
                    >
                      <Copy className="h-3.5 w-3.5" />
                    </button>
                    <button
                      onClick={() => onEdit(invite)}
                      className="p-2 text-slate-500 hover:text-amber-600 dark:text-slate-300 rounded-lg transition active:bg-slate-100 dark:active:bg-slate-900 cursor-pointer"
                      title="Ubah profil"
                    >
                      <Edit className="h-3.5 w-3.5" />
                    </button>
                    <button
                      onClick={() => onDelete(invite)}
                      className="p-2 text-slate-400 hover:text-rose-600 rounded-lg transition active:bg-rose-50 dark:active:bg-rose-950/20 cursor-pointer"
                      title="Hapus peserta"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>

                  {/* Tombol Kirim WA Paling Dominan (Mudah Diklik di HP) */}
                  <button
                    onClick={() => onSendToWhatsApp(invite)}
                    className="px-3.5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white dark:bg-emerald-500 dark:hover:bg-emerald-600 rounded-xl text-xs font-bold leading-none inline-flex items-center gap-1.5 transition shadow-sm cursor-pointer active:scale-95 duration-100"
                    title={invite.isCompleted ? "Kirim ulang konfirmasi selesai" : "Kirim link/ingatkan pengisian"}
                  >
                    <MessageCircle className="h-4 w-4 fill-white" />
                    <span>Kirim WA</span>
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
