'use client';

import { useState, useEffect } from 'react';
import { Download, Trash2, AlertCircle, Clock } from 'lucide-react';
import { apiFetch } from '@/lib/csrf/client';

interface WaitlistEntry {
  id: string;
  email: string;
  name: string | null;
  source: string | null;
  createdAt: string;
}

export default function AdminWaitlistPage() {
  const [entries, setEntries] = useState<WaitlistEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState<string | null>(null);

  const fetchWaitlist = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const res = await apiFetch('/api/admin/waitlist');
      if (!res.ok) throw new Error('Failed to fetch waitlist');
      const data = await res.json();
      setEntries(data.entries || []);
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchWaitlist();
  }, []);

  const handleDelete = async (id: string) => {
    if (!confirm('Diesen Eintrag wirklich von der Warteliste entfernen?')) return;
    
    try {
      setIsDeleting(id);
      const res = await apiFetch(`/api/admin/waitlist/${id}`, {
        method: 'DELETE',
      });
      if (!res.ok) throw new Error('Failed to delete entry');
      
      setEntries(entries.filter(entry => entry.id !== id));
    } catch (err: any) {
      alert(err.message || 'Löschen fehlgeschlagen');
    } finally {
      setIsDeleting(null);
    }
  };

  const exportCSV = () => {
    if (entries.length === 0) return;
    
    const headers = ['Email', 'Name', 'Source', 'Date Added'];
    const csvContent = [
      headers.join(','),
      ...entries.map(e => [
        `"${e.email}"`,
        `"${e.name || ''}"`,
        `"${e.source || ''}"`,
        `"${new Date(e.createdAt).toISOString()}"`
      ].join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `waitlist_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const formatRelativeTime = (isoString: string) => {
    const date = new Date(isoString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 60) return `vor ${diffMins} min`;
    if (diffHours < 24) return `vor ${diffHours} h`;
    if (diffDays === 1) return `gestern`;
    return `vor ${diffDays} Tagen`;
  };

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans">
            Warteliste
          </h1>
          <span className="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-0.5 rounded-full text-xs font-mono font-bold">
            {isLoading ? '...' : entries.length} Einträge
          </span>
        </div>
        
        <button 
          onClick={exportCSV}
          disabled={isLoading || entries.length === 0}
          className="px-4 py-2 bg-white hover:bg-slate-50 border border-slate-200 text-slate-800 rounded-xl text-xs sm:text-sm font-semibold transition-all flex items-center gap-2 shadow-xs disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Download size={15} />
          CSV Exportieren
        </button>
      </div>

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3 text-red-700 text-xs sm:text-sm">
          <AlertCircle size={18} />
          <span>{error}</span>
        </div>
      )}

      <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-xs">
        <div className="overflow-x-auto">
          <table className="w-full text-xs sm:text-sm text-left">
            <thead className="text-[11px] font-mono text-slate-500 uppercase bg-slate-50 border-b border-slate-200">
              <tr>
                <th className="px-6 py-3.5 font-bold">E-Mail</th>
                <th className="px-6 py-3.5 font-bold">Name</th>
                <th className="px-6 py-3.5 font-bold">Quelle / Kampagne</th>
                <th className="px-6 py-3.5 font-bold">Eingetragen</th>
                <th className="px-6 py-3.5 font-bold text-right">Aktionen</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {isLoading ? (
                [...Array(3)].map((_, i) => (
                  <tr key={i} className="animate-pulse">
                    <td className="px-6 py-4"><div className="h-4 w-48 bg-slate-200 rounded"></div></td>
                    <td className="px-6 py-4"><div className="h-4 w-32 bg-slate-200 rounded"></div></td>
                    <td className="px-6 py-4"><div className="h-4 w-24 bg-slate-200 rounded"></div></td>
                    <td className="px-6 py-4"><div className="h-4 w-20 bg-slate-200 rounded"></div></td>
                    <td className="px-6 py-4"><div className="h-8 w-8 bg-slate-200 rounded ml-auto"></div></td>
                  </tr>
                ))
              ) : entries.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-16 text-center">
                    <div className="flex flex-col items-center justify-center text-slate-400 space-y-2">
                      <Clock size={28} className="text-slate-300" />
                      <p className="text-sm font-medium">Die Warteliste ist momentan leer.</p>
                    </div>
                  </td>
                </tr>
              ) : (
                entries.map((entry) => (
                  <tr key={entry.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-6 py-3.5 whitespace-nowrap font-semibold text-slate-900">
                      {entry.email}
                    </td>
                    <td className="px-6 py-3.5 whitespace-nowrap text-slate-700 font-medium">
                      {entry.name || '-'}
                    </td>
                    <td className="px-6 py-3.5 whitespace-nowrap text-slate-500 font-mono text-xs">
                      {entry.source || '-'}
                    </td>
                    <td className="px-6 py-3.5 whitespace-nowrap text-slate-500 font-mono text-xs">
                      <div className="flex items-center gap-1.5" title={new Date(entry.createdAt).toLocaleString()}>
                        <Clock size={13} className="text-slate-400" />
                        {formatRelativeTime(entry.createdAt)}
                      </div>
                    </td>
                    <td className="px-6 py-3.5 whitespace-nowrap text-right">
                      <button 
                        onClick={() => handleDelete(entry.id)}
                        disabled={isDeleting === entry.id}
                        className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
                        title="Von Warteliste löschen"
                      >
                        <Trash2 size={16} />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
