'use client';

import { useState, useEffect } from 'react';
import { Search, RefreshCw, AlertCircle, ChevronDown, ChevronUp, Users } from 'lucide-react';
import { apiFetch } from '@/lib/csrf/client';

interface User {
  id: string;
  email: string;
  name: string | null;
  plan: 'free' | 'weekly' | 'annual' | 'lifetime';
  scanCount: string | number;
  company: string | null;
  useCase: string | null;
  monthlyVolume: string | null;
  exportFormat: string | null;
  referralSource: string | null;
  onboardingCompletedAt: string | null;
  createdAt: string;
  updatedAt: string;
}

export default function AdminUsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [planFilter, setPlanFilter] = useState<string>('all');
  const [useCaseFilter, setUseCaseFilter] = useState<string>('all');
  const [sortField, setSortField] = useState<keyof User>('createdAt');
  const [sortDesc, setSortDesc] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  const fetchUsers = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const query = new URLSearchParams({
        search: searchQuery,
        plan: planFilter,
        useCase: useCaseFilter,
        sort: sortField,
        order: sortDesc ? 'desc' : 'asc',
        page: page.toString(),
        limit: '20'
      });
      const res = await apiFetch(`/api/admin/users?${query}`);
      if (!res.ok) throw new Error('Failed to fetch users');
      const data = await res.json();
      setUsers(data.users || []);
      setTotalPages(Math.ceil((data.total || 1) / 20) || 1);
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [planFilter, useCaseFilter, sortField, sortDesc, page]);

  // Use a debounced search for text input
  useEffect(() => {
    const timer = setTimeout(() => {
      setPage(1); // Reset to first page on search
      fetchUsers();
    }, 500);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  const handleSort = (field: keyof User) => {
    if (sortField === field) {
      setSortDesc(!sortDesc);
    } else {
      setSortField(field);
      setSortDesc(true);
    }
    setPage(1);
  };

  const formatDate = (isoString?: string | null) => {
    if (!isoString) return '-';
    return new Date(isoString).toLocaleDateString('de-DE', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const getPlanBadge = (plan: string) => {
    switch (plan) {
      case 'weekly': return <span className="bg-sky-50 text-sky-700 border border-sky-200 px-2 py-0.5 rounded text-xs font-semibold">Weekly</span>;
      case 'annual': return <span className="bg-emerald-50 text-emerald-700 border border-emerald-200 px-2 py-0.5 rounded text-xs font-semibold">Annual</span>;
      case 'lifetime': return <span className="bg-amber-50 text-amber-800 border border-amber-200 px-2 py-0.5 rounded text-xs font-semibold">Lifetime</span>;
      default: return <span className="bg-slate-100 text-slate-700 border border-slate-200 px-2 py-0.5 rounded text-xs font-medium">Free</span>;
    }
  };

  const getPersonaBadge = (useCase: string | null) => {
    switch (useCase) {
      case 'freelancer': return <span className="bg-emerald-50 text-emerald-800 px-2 py-0.5 rounded text-[11px] font-medium border border-emerald-200">💼 Freelancer</span>;
      case 'small_business': return <span className="bg-blue-50 text-blue-800 px-2 py-0.5 rounded text-[11px] font-medium border border-blue-200">🏢 KMU</span>;
      case 'accountant': return <span className="bg-indigo-50 text-indigo-800 px-2 py-0.5 rounded text-[11px] font-medium border border-indigo-200">Team</span>;
      case 'personal': return <span className="bg-slate-100 text-slate-700 px-2 py-0.5 rounded text-[11px] font-medium border border-slate-200">🏠 Privat</span>;
      default: return <span className="text-slate-400 text-xs">-</span>;
    }
  };

  const getVolumeBadge = (volume: string | null) => {
    switch (volume) {
      case 'tier_1_10': return <span className="text-slate-600 text-xs">1-10/mo</span>;
      case 'tier_10_50': return <span className="text-teal-700 text-xs font-medium">10-50/mo</span>;
      case 'tier_50_150': return <span className="text-amber-700 text-xs font-semibold">50-150/mo</span>;
      case 'tier_150_plus': return <span className="text-rose-700 text-xs font-bold">150+/mo 🔥</span>;
      default: return <span className="text-slate-400 text-xs">-</span>;
    }
  };

  const getExportBadge = (format: string | null) => {
    switch (format) {
      case 'excel_csv': return <span className="text-slate-800 text-xs font-medium">Excel/CSV</span>;
      case 'datev': return <span className="text-sky-700 text-xs font-semibold">CSV</span>;
      case 'lexoffice_sevdesk': return <span className="text-emerald-700 text-xs font-semibold">Lexoffice/SevDesk</span>;
      case 'pdf_bundle': return <span className="text-purple-700 text-xs">PDF Bundle</span>;
      case 'google_sheets': return <span className="text-amber-700 text-xs">Google Sheets</span>;
      default: return <span className="text-slate-400 text-xs">-</span>;
    }
  };

  const SortIcon = ({ field }: { field: keyof User }) => {
    if (sortField !== field) return <span className="w-4 inline-block"></span>;
    return sortDesc ? <ChevronDown size={14} className="inline ml-1 text-slate-500" /> : <ChevronUp size={14} className="inline ml-1 text-slate-500" />;
  };

  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>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans">
            Benutzer & Onboarding
          </h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">
            Accounts, Tarife, Onboarding-Personas und Belegkontingente.
          </p>
        </div>
        
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
            <input 
              type="text" 
              placeholder="E-Mail oder Name suchen..." 
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-xs sm:text-sm focus:outline-none focus:border-slate-900 focus:ring-1 focus:ring-slate-900 w-56 text-slate-900 placeholder:text-slate-400 shadow-xs"
            />
          </div>
          
          <select 
            value={planFilter}
            onChange={(e) => { setPlanFilter(e.target.value); setPage(1); }}
            className="px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs sm:text-sm focus:outline-none focus:border-slate-900 focus:ring-1 focus:ring-slate-900 text-slate-800 shadow-xs"
          >
            <option value="all">Alle Tarife</option>
            <option value="free">Free</option>
            <option value="weekly">Weekly</option>
            <option value="annual">Annual</option>
            <option value="lifetime">Lifetime</option>
          </select>

          <select 
            value={useCaseFilter}
            onChange={(e) => { setUseCaseFilter(e.target.value); setPage(1); }}
            className="px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs sm:text-sm focus:outline-none focus:border-slate-900 focus:ring-1 focus:ring-slate-900 text-slate-800 shadow-xs"
          >
            <option value="all">Alle Personas</option>
            <option value="freelancer">💼 Freelancer</option>
            <option value="small_business">🏢 KMU / Gewerbe</option>
            <option value="accountant">Team / Organisation</option>
            <option value="personal">🏠 Privat</option>
          </select>

          <button 
            onClick={() => fetchUsers()}
            className="p-2 text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-50 rounded-xl transition-colors shadow-xs"
            title="Liste aktualisieren"
          >
            <RefreshCw size={16} className={isLoading ? "animate-spin" : ""} />
          </button>
        </div>
      </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 onClick={() => handleSort('email')} className="px-5 py-3.5 font-bold cursor-pointer hover:text-slate-900 transition-colors">
                  E-Mail / Name <SortIcon field="email" />
                </th>
                <th onClick={() => handleSort('plan')} className="px-4 py-3.5 font-bold cursor-pointer hover:text-slate-900 transition-colors">
                  Tarif <SortIcon field="plan" />
                </th>
                <th className="px-4 py-3.5 font-bold">Persona</th>
                <th className="px-4 py-3.5 font-bold">Volumen</th>
                <th className="px-4 py-3.5 font-bold">Export Format</th>
                <th className="px-4 py-3.5 font-bold">Kanal</th>
                <th onClick={() => handleSort('scanCount')} className="px-4 py-3.5 font-bold cursor-pointer hover:text-slate-900 transition-colors text-right">
                  Scans <SortIcon field="scanCount" />
                </th>
                <th onClick={() => handleSort('createdAt')} className="px-5 py-3.5 font-bold cursor-pointer hover:text-slate-900 transition-colors">
                  Registriert <SortIcon field="createdAt" />
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {isLoading ? (
                [...Array(5)].map((_, i) => (
                  <tr key={i} className="animate-pulse">
                    <td className="px-5 py-4"><div className="h-4 w-32 bg-slate-200 rounded mb-1.5"></div><div className="h-3 w-24 bg-slate-100 rounded"></div></td>
                    <td className="px-4 py-4"><div className="h-5 w-16 bg-slate-200 rounded"></div></td>
                    <td className="px-4 py-4"><div className="h-4 w-20 bg-slate-200 rounded"></div></td>
                    <td className="px-4 py-4"><div className="h-4 w-16 bg-slate-200 rounded"></div></td>
                    <td className="px-4 py-4"><div className="h-4 w-20 bg-slate-200 rounded"></div></td>
                    <td className="px-4 py-4"><div className="h-4 w-16 bg-slate-200 rounded"></div></td>
                    <td className="px-4 py-4 text-right"><div className="h-4 w-8 bg-slate-200 rounded ml-auto"></div></td>
                    <td className="px-5 py-4"><div className="h-4 w-20 bg-slate-200 rounded"></div></td>
                  </tr>
                ))
              ) : users.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-slate-400">
                    Keine Benutzer für diesen Filter gefunden.
                  </td>
                </tr>
              ) : (
                users.map((user) => (
                  <tr key={user.id} className="hover:bg-slate-50/80 transition-colors">
                    <td className="px-5 py-3.5 whitespace-nowrap">
                      <div className="font-semibold text-slate-900">{user.email}</div>
                      {user.name && <div className="text-xs text-slate-400 mt-0.5">{user.name}</div>}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap">
                      {getPlanBadge(user.plan)}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap">
                      {getPersonaBadge(user.useCase)}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap">
                      {getVolumeBadge(user.monthlyVolume)}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap">
                      {getExportBadge(user.exportFormat)}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap text-xs text-slate-500 font-mono">
                      {user.referralSource ? user.referralSource : '-'}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap font-mono font-bold text-right text-slate-800">
                      {Number(user.scanCount || 0).toLocaleString('de-DE')}
                    </td>
                    <td className="px-5 py-3.5 whitespace-nowrap text-slate-500 text-xs font-mono">
                      {formatDate(user.createdAt)}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        
        {/* Pagination */}
        {!isLoading && users.length > 0 && (
          <div className="px-6 py-4 border-t border-slate-200 flex items-center justify-between text-xs sm:text-sm text-slate-500 bg-slate-50">
            <div>
              Seite <span className="font-bold text-slate-900">{page}</span> von <span className="font-bold text-slate-900">{totalPages}</span>
            </div>
            <div className="flex gap-2">
              <button 
                onClick={() => setPage(Math.max(1, page - 1))}
                disabled={page === 1}
                className="px-3 py-1.5 bg-white border border-slate-200 rounded-lg hover:bg-slate-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-slate-800 font-medium"
              >
                Zurück
              </button>
              <button 
                onClick={() => setPage(Math.min(totalPages, page + 1))}
                disabled={page === totalPages}
                className="px-3 py-1.5 bg-white border border-slate-200 rounded-lg hover:bg-slate-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-slate-800 font-medium"
              >
                Weiter
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
