'use client';

import { useState, useMemo, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import {
  Users,
  TrendingUp,
  Calendar,
  Download,
  Trash2,
  Search,
  LogOut,
  ChevronDown,
  ChevronUp,
  Flame,
  X,
  Eye,
  XCircle,
} from 'lucide-react';
import type { AdminRegistration, DashboardStats } from '@/lib/actions/admin';
import { deleteRegistration } from '@/lib/actions/admin';

const STACK_LABELS: Record<string, string> = {
  web_development: 'Web Development',
  data_analytics: 'Data Analytics',
  product_design: 'Product Design',
  digital_marketing: 'Digital Marketing',
  ai_automation: 'AI & Automation',
};

const STACK_COLORS: Record<string, string> = {
  web_development: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
  data_analytics: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30',
  product_design: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
  digital_marketing: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
  ai_automation: 'bg-violet-500/20 text-violet-300 border-violet-500/30',
};

const AGE_LABELS: Record<string, string> = {
  under_18: 'Under 18',
  '18_25': '18–25',
  '26_30': '26–30',
  '31_35': '31–35',
  '36_plus': '36+',
};

const GENDER_LABELS: Record<string, string> = {
  male: 'Male',
  female: 'Female',
  prefer_not_to_say: 'Prefer not to say',
};

type SortKey = keyof AdminRegistration;

function StatCard({
  icon: Icon,
  label,
  value,
  sub,
  accent,
}: {
  icon: React.ElementType;
  label: string;
  value: string | number;
  sub?: string;
  accent?: string;
}) {
  return (
    <div className="bg-gray-900 border border-gray-800 rounded-2xl p-5">
      <div className="flex items-start justify-between mb-4">
        <div
          className={`w-10 h-10 rounded-xl flex items-center justify-center ${accent || 'bg-orange-500/20'}`}
        >
          <Icon className={`w-5 h-5 ${accent ? 'text-white' : 'text-orange-400'}`} />
        </div>
      </div>
      <p className="text-3xl font-black text-white tracking-tight">{value}</p>
      <p className="text-sm font-semibold text-gray-300 mt-0.5">{label}</p>
      {sub && <p className="text-xs text-gray-500 mt-1">{sub}</p>}
    </div>
  );
}

function BarChart({
  data,
  colorClass,
}: {
  data: Record<string, number>;
  colorClass?: string;
}) {
  const max = Math.max(...Object.values(data), 1);
  const total = Object.values(data).reduce((a, b) => a + b, 0);

  return (
    <div className="space-y-2.5">
      {Object.entries(data)
        .sort((a, b) => b[1] - a[1])
        .map(([key, val]) => (
          <div key={key}>
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-gray-400 truncate max-w-[60%]">
                {STACK_LABELS[key] || AGE_LABELS[key] || GENDER_LABELS[key] || key}
              </span>
              <span className="text-xs font-bold text-gray-300">
                {val}{' '}
                <span className="text-gray-500 font-normal">
                  ({total ? Math.round((val / total) * 100) : 0}%)
                </span>
              </span>
            </div>
            <div className="h-2 bg-gray-800 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all duration-500 ${colorClass || 'bg-orange-500'}`}
                style={{ width: `${(val / max) * 100}%` }}
              />
            </div>
          </div>
        ))}
    </div>
  );
}

// Modal for viewing motivation
function MotivationModal({
  reg,
  onClose,
}: {
  reg: AdminRegistration;
  onClose: () => void;
}) {
  return (
    <div
      className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-gray-900 border border-gray-700 rounded-2xl p-6 max-w-lg w-full shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-start justify-between mb-4">
          <div>
            <h3 className="text-white font-bold">{reg.fullName}</h3>
            <p className="text-gray-400 text-sm">{reg.email}</p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
        <div className="bg-gray-800 rounded-xl p-4">
          <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">
            Motivation
          </p>
          <p className="text-gray-200 text-sm leading-relaxed">{reg.motivation}</p>
        </div>
        <div className="grid grid-cols-2 gap-3 mt-4">
          <div className="bg-gray-800 rounded-xl p-3">
            <p className="text-xs text-gray-500 mb-1">Track</p>
            <p className="text-sm font-medium text-gray-200">
              {STACK_LABELS[reg.stack] || reg.stack}
            </p>
          </div>
          <div className="bg-gray-800 rounded-xl p-3">
            <p className="text-xs text-gray-500 mb-1">Heard From</p>
            <p className="text-sm font-medium text-gray-200">{reg.heardFrom}</p>
          </div>
          <div className="bg-gray-800 rounded-xl p-3">
            <p className="text-xs text-gray-500 mb-1">Age Range</p>
            <p className="text-sm font-medium text-gray-200">
              {AGE_LABELS[reg.ageRange] || reg.ageRange}
            </p>
          </div>
          <div className="bg-gray-800 rounded-xl p-3">
            <p className="text-xs text-gray-500 mb-1">Gender</p>
            <p className="text-sm font-medium text-gray-200">
              {GENDER_LABELS[reg.gender] || reg.gender}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function AdminDashboardClient({
  stats,
  registrations,
}: {
  stats: DashboardStats;
  registrations: AdminRegistration[];
}) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const [search, setSearch] = useState('');
  const [stackFilter, setStackFilter] = useState('');
  const [genderFilter, setGenderFilter] = useState('');
  const [sortKey, setSortKey] = useState<SortKey>('createdAt');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [viewReg, setViewReg] = useState<AdminRegistration | null>(null);

  const handleLogout = async () => {
    await fetch('/api/admin/logout', { method: 'POST' });
    router.push('/admin/login');
  };

  const handleDelete = async (id: string) => {
    setDeletingId(id);
    const result = await deleteRegistration(id);
    setDeletingId(null);
    setConfirmDeleteId(null);
    if (result.success) {
      startTransition(() => {
        router.refresh();
      });
    } else {
      alert(result.error || 'Failed to delete.');
    }
  };

  const handleSort = (key: SortKey) => {
    if (sortKey === key) {
      setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    } else {
      setSortKey(key);
      setSortDir('asc');
    }
  };

  const filtered = useMemo(() => {
    let rows = [...registrations];

    if (search.trim()) {
      const q = search.toLowerCase();
      rows = rows.filter(
        (r) =>
          r.fullName.toLowerCase().includes(q) ||
          r.email.toLowerCase().includes(q) ||
          r.phone.includes(q)
      );
    }

    if (stackFilter) rows = rows.filter((r) => r.stack === stackFilter);
    if (genderFilter) rows = rows.filter((r) => r.gender === genderFilter);

    rows.sort((a, b) => {
      const av = a[sortKey];
      const bv = b[sortKey];
      let cmp = 0;
      if (av instanceof Date && bv instanceof Date) {
        cmp = av.getTime() - bv.getTime();
      } else {
        cmp = String(av).localeCompare(String(bv));
      }
      return sortDir === 'asc' ? cmp : -cmp;
    });

    return rows;
  }, [registrations, search, stackFilter, genderFilter, sortKey, sortDir]);

  const exportCSV = () => {
    const headers = [
      'Full Name',
      'Email',
      'Phone',
      'Gender',
      'Age Range',
      'Track',
      'Heard From',
      'Registered At',
    ];
    const rows = filtered.map((r) => [
      r.fullName,
      r.email,
      r.phone,
      GENDER_LABELS[r.gender] || r.gender,
      AGE_LABELS[r.ageRange] || r.ageRange,
      STACK_LABELS[r.stack] || r.stack,
      r.heardFrom,
      new Date(r.createdAt).toLocaleString(),
    ]);

    const csv = [headers, ...rows]
      .map((row) => row.map((cell) => `"${cell}"`).join(','))
      .join('\n');

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `ignite-100-registrations-${Date.now()}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const SortIcon = ({ field }: { field: SortKey }) =>
    sortKey === field ? (
      sortDir === 'asc' ? (
        <ChevronUp className="w-3 h-3" />
      ) : (
        <ChevronDown className="w-3 h-3" />
      )
    ) : (
      <ChevronDown className="w-3 h-3 opacity-30" />
    );

  return (
    <div className="min-h-screen bg-gray-950">
      {/* Header */}
      <header className="bg-gray-900/80 backdrop-blur border-b border-gray-800 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-orange-500 rounded-lg flex items-center justify-center">
              <Flame className="w-4 h-4 text-white" />
            </div>
            <div>
              <span className="text-white font-bold text-sm">TechTan Admin</span>
              <span className="text-gray-500 text-xs ml-2">Ignite-100</span>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="flex items-center gap-2 text-gray-400 hover:text-white text-sm font-medium transition-colors px-3 py-1.5 rounded-lg hover:bg-gray-800"
          >
            <LogOut className="w-4 h-4" />
            Logout
          </button>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 py-8 space-y-8">
        {/* Page title */}
        <div>
          <h1 className="text-2xl font-black text-white tracking-tight">
            Dashboard
          </h1>
          <p className="text-gray-400 text-sm mt-1">
            Ignite-100 registration overview
          </p>
        </div>

        {/* Stats row */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
          <StatCard
            icon={Users}
            label="Total Registrations"
            value={stats.total}
            sub="All time"
            accent="bg-orange-500"
          />
          <StatCard
            icon={TrendingUp}
            label="New This Week"
            value={stats.recentCount}
            sub="Last 7 days"
            accent="bg-emerald-500/20"
          />
          <StatCard
            icon={Calendar}
            label="Most Popular Track"
            value={
              Object.entries(stats.byStack).sort((a, b) => b[1] - a[1])[0]
                ? STACK_LABELS[
                    Object.entries(stats.byStack).sort(
                      (a, b) => b[1] - a[1]
                    )[0][0]
                  ] || '—'
                : '—'
            }
            sub={
              Object.entries(stats.byStack).sort((a, b) => b[1] - a[1])[0]
                ? `${Object.entries(stats.byStack).sort((a, b) => b[1] - a[1])[0][1]} applicants`
                : ''
            }
            accent="bg-blue-500/20"
          />
          <StatCard
            icon={Users}
            label="Showing (filtered)"
            value={filtered.length}
            sub={`of ${stats.total} total`}
            accent="bg-purple-500/20"
          />
        </div>

        {/* Charts */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div className="bg-gray-900 border border-gray-800 rounded-2xl p-5">
            <h3 className="text-sm font-bold text-gray-300 mb-4 uppercase tracking-wide">
              By Track
            </h3>
            <BarChart data={stats.byStack} colorClass="bg-orange-500" />
          </div>
          <div className="bg-gray-900 border border-gray-800 rounded-2xl p-5">
            <h3 className="text-sm font-bold text-gray-300 mb-4 uppercase tracking-wide">
              By Age Range
            </h3>
            <BarChart data={stats.byAgeRange} colorClass="bg-blue-500" />
          </div>
          <div className="bg-gray-900 border border-gray-800 rounded-2xl p-5">
            <h3 className="text-sm font-bold text-gray-300 mb-4 uppercase tracking-wide">
              How They Heard
            </h3>
            <BarChart data={stats.byHeardFrom} colorClass="bg-emerald-500" />
          </div>
        </div>

        {/* Table section */}
        <div className="bg-gray-900 border border-gray-800 rounded-2xl overflow-hidden">
          {/* Table header controls */}
          <div className="p-4 sm:p-5 border-b border-gray-800 flex flex-col sm:flex-row items-start sm:items-center gap-3">
            <div className="flex-1 relative w-full sm:max-w-xs">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search name, email, phone…"
                className="w-full pl-9 pr-8 py-2.5 bg-gray-800 border border-gray-700 rounded-xl text-sm text-white placeholder-gray-500 outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500/30 transition-all"
              />
              {search && (
                <button
                  onClick={() => setSearch('')}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
                >
                  <XCircle className="w-4 h-4" />
                </button>
              )}
            </div>

            <div className="flex items-center gap-2 flex-wrap">
              {/* Stack filter */}
              <select
                value={stackFilter}
                onChange={(e) => setStackFilter(e.target.value)}
                className="bg-gray-800 border border-gray-700 text-sm text-gray-300 rounded-lg px-3 py-2 outline-none focus:border-orange-500 cursor-pointer"
              >
                <option value="">All Tracks</option>
                {Object.entries(STACK_LABELS).map(([val, label]) => (
                  <option key={val} value={val}>
                    {label}
                  </option>
                ))}
              </select>

              {/* Gender filter */}
              <select
                value={genderFilter}
                onChange={(e) => setGenderFilter(e.target.value)}
                className="bg-gray-800 border border-gray-700 text-sm text-gray-300 rounded-lg px-3 py-2 outline-none focus:border-orange-500 cursor-pointer"
              >
                <option value="">All Genders</option>
                {Object.entries(GENDER_LABELS).map(([val, label]) => (
                  <option key={val} value={val}>
                    {label}
                  </option>
                ))}
              </select>

              {/* Export button */}
              <button
                onClick={exportCSV}
                className="flex items-center gap-1.5 bg-gray-800 hover:bg-gray-700 border border-gray-700 text-gray-300 hover:text-white text-sm font-medium px-3 py-2 rounded-lg transition-colors"
              >
                <Download className="w-4 h-4" />
                Export CSV
              </button>
            </div>
          </div>

          {/* Count */}
          <div className="px-5 py-2.5 bg-gray-900/50 border-b border-gray-800">
            <p className="text-xs text-gray-500">
              Showing{' '}
              <span className="text-gray-300 font-semibold">{filtered.length}</span>{' '}
              registration{filtered.length !== 1 ? 's' : ''}
              {(search || stackFilter || genderFilter) && ' (filtered)'}
            </p>
          </div>

          {/* Table */}
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-800">
                  {[
                    { key: 'fullName' as SortKey, label: 'Name' },
                    { key: 'email' as SortKey, label: 'Email' },
                    { key: 'phone' as SortKey, label: 'Phone' },
                    { key: 'stack' as SortKey, label: 'Track' },
                    { key: 'gender' as SortKey, label: 'Gender' },
                    { key: 'ageRange' as SortKey, label: 'Age' },
                    { key: 'heardFrom' as SortKey, label: 'Source' },
                    { key: 'createdAt' as SortKey, label: 'Registered' },
                  ].map(({ key, label }) => (
                    <th
                      key={key}
                      onClick={() => handleSort(key)}
                      className="text-left px-4 py-3 text-xs font-bold text-gray-500 uppercase tracking-widest cursor-pointer hover:text-gray-300 transition-colors whitespace-nowrap select-none"
                    >
                      <div className="flex items-center gap-1">
                        {label}
                        <SortIcon field={key} />
                      </div>
                    </th>
                  ))}
                  <th className="text-left px-4 py-3 text-xs font-bold text-gray-500 uppercase tracking-widest">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 ? (
                  <tr>
                    <td
                      colSpan={9}
                      className="text-center py-16 text-gray-500 text-sm"
                    >
                      No registrations found
                    </td>
                  </tr>
                ) : (
                  filtered.map((reg) => (
                    <tr
                      key={reg.id}
                      className="border-b border-gray-800/50 hover:bg-gray-800/30 transition-colors group"
                    >
                      <td className="px-4 py-3 text-sm font-medium text-white whitespace-nowrap">
                        {reg.fullName}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap">
                        {reg.email}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap">
                        {reg.phone}
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <span
                          className={`inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-semibold border ${
                            STACK_COLORS[reg.stack] ||
                            'bg-gray-700 text-gray-300 border-gray-600'
                          }`}
                        >
                          {STACK_LABELS[reg.stack] || reg.stack}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap capitalize">
                        {GENDER_LABELS[reg.gender] || reg.gender}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap">
                        {AGE_LABELS[reg.ageRange] || reg.ageRange}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap">
                        {reg.heardFrom}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">
                        {new Date(reg.createdAt).toLocaleDateString('en-NG', {
                          day: 'numeric',
                          month: 'short',
                          year: 'numeric',
                        })}
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <div className="flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
                          {/* View motivation */}
                          <button
                            onClick={() => setViewReg(reg)}
                            title="View motivation"
                            className="p-1.5 text-gray-400 hover:text-blue-400 hover:bg-blue-500/10 rounded-lg transition-colors"
                          >
                            <Eye className="w-4 h-4" />
                          </button>

                          {/* Delete */}
                          {confirmDeleteId === reg.id ? (
                            <div className="flex items-center gap-1">
                              <button
                                onClick={() => handleDelete(reg.id)}
                                disabled={deletingId === reg.id}
                                className="text-xs px-2 py-1 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-md font-medium transition-colors"
                              >
                                {deletingId === reg.id ? '…' : 'Confirm'}
                              </button>
                              <button
                                onClick={() => setConfirmDeleteId(null)}
                                className="text-xs px-2 py-1 bg-gray-700 text-gray-300 hover:bg-gray-600 rounded-md font-medium transition-colors"
                              >
                                Cancel
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => setConfirmDeleteId(reg.id)}
                              title="Delete registration"
                              className="p-1.5 text-gray-400 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </main>

      {/* Motivation modal */}
      {viewReg && (
        <MotivationModal reg={viewReg} onClose={() => setViewReg(null)} />
      )}
    </div>
  );
}