import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { getLoginUrl } from "@/const";
import { useState, useMemo, useEffect } from "react";
import { Link } from "wouter";
import {
  Mail,
  Inbox,
  CheckCircle2,
  Archive,
  MessageSquare,
  ArrowLeft,
  Clock,
  Building2,
  Factory,
  Eye,
  Reply,
  ArchiveIcon,
  RotateCcw,
  Loader2,
  ShieldAlert,
  ChevronDown,
  ChevronUp,
  ExternalLink,
} from "lucide-react";
import { toast } from "sonner";

type StatusFilter = "all" | "new" | "read" | "replied" | "archived";

const statusConfig: Record<string, { label: string; color: string; bg: string; icon: typeof Inbox }> = {
  new: { label: "New", color: "text-blue-600", bg: "bg-blue-50 border-blue-200", icon: Inbox },
  read: { label: "Read", color: "text-amber-600", bg: "bg-amber-50 border-amber-200", icon: Eye },
  replied: { label: "Replied", color: "text-green-600", bg: "bg-green-50 border-green-200", icon: CheckCircle2 },
  archived: { label: "Archived", color: "text-gray-500", bg: "bg-gray-50 border-gray-200", icon: Archive },
};

function StatusBadge({ status }: { status: string }) {
  const config = statusConfig[status] || statusConfig.new;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${config.bg} ${config.color}`}>
      <config.icon className="w-3 h-3" />
      {config.label}
    </span>
  );
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: number; icon: typeof Inbox; color: string }) {
  return (
    <div className="bg-white rounded-xl border border-navy/5 p-5 shadow-sm hover:shadow-md transition-shadow">
      <div className="flex items-center justify-between mb-3">
        <div className={`p-2.5 rounded-lg ${color}`}>
          <Icon className="w-5 h-5" />
        </div>
        <span className="text-2xl font-bold font-heading text-navy">{value}</span>
      </div>
      <p className="text-sm text-slate-dark/60 font-medium">{label}</p>
    </div>
  );
}

function SubmissionRow({
  submission,
  expanded,
  onToggle,
  onUpdateStatus,
  isUpdating,
}: {
  submission: any;
  expanded: boolean;
  onToggle: () => void;
  onUpdateStatus: (id: number, status: "new" | "read" | "replied" | "archived") => void;
  isUpdating: boolean;
}) {
  const date = new Date(submission.createdAt);
  const formattedDate = date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
  const formattedTime = date.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
  });

  return (
    <div className={`border rounded-xl transition-all ${expanded ? "border-teal/30 shadow-md shadow-teal/5" : "border-navy/5 hover:border-navy/15"}`}>
      {/* Row header */}
      <button
        onClick={onToggle}
        className="w-full text-left p-4 flex items-center gap-4"
      >
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-3 mb-1">
            <span className="font-semibold text-navy truncate">{submission.name}</span>
            <StatusBadge status={submission.status} />
          </div>
          <div className="flex items-center gap-4 text-sm text-slate-dark/50">
            <span className="flex items-center gap-1">
              <Mail className="w-3.5 h-3.5" />
              {submission.email}
            </span>
            {submission.company && (
              <span className="flex items-center gap-1">
                <Building2 className="w-3.5 h-3.5" />
                {submission.company}
              </span>
            )}
            {submission.industry && (
              <span className="flex items-center gap-1">
                <Factory className="w-3.5 h-3.5" />
                {submission.industry}
              </span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-3 shrink-0">
          <span className="text-xs text-slate-dark/40 flex items-center gap-1">
            <Clock className="w-3 h-3" />
            {formattedDate} {formattedTime}
          </span>
          {expanded ? (
            <ChevronUp className="w-4 h-4 text-navy/30" />
          ) : (
            <ChevronDown className="w-4 h-4 text-navy/30" />
          )}
        </div>
      </button>

      {/* Expanded content */}
      {expanded && (
        <div className="px-4 pb-4 border-t border-navy/5">
          <div className="pt-4">
            {/* Message */}
            <div className="bg-warm-white rounded-lg p-4 mb-4">
              <h4 className="text-xs font-semibold text-navy/50 uppercase tracking-wider mb-2">Message</h4>
              <p className="text-navy/80 leading-relaxed whitespace-pre-wrap">{submission.message}</p>
            </div>

            {/* Actions */}
            <div className="flex items-center gap-2 flex-wrap">
              {submission.status !== "read" && (
                <button
                  onClick={() => onUpdateStatus(submission.id, "read")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-amber-700 bg-amber-50 hover:bg-amber-100 border border-amber-200 rounded-lg transition-colors disabled:opacity-50"
                >
                  <Eye className="w-3.5 h-3.5" />
                  Mark as Read
                </button>
              )}
              {submission.status !== "replied" && (
                <button
                  onClick={() => onUpdateStatus(submission.id, "replied")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-green-700 bg-green-50 hover:bg-green-100 border border-green-200 rounded-lg transition-colors disabled:opacity-50"
                >
                  <Reply className="w-3.5 h-3.5" />
                  Mark as Replied
                </button>
              )}
              {submission.status !== "archived" && (
                <button
                  onClick={() => onUpdateStatus(submission.id, "archived")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-gray-600 bg-gray-50 hover:bg-gray-100 border border-gray-200 rounded-lg transition-colors disabled:opacity-50"
                >
                  <ArchiveIcon className="w-3.5 h-3.5" />
                  Archive
                </button>
              )}
              {submission.status !== "new" && (
                <button
                  onClick={() => onUpdateStatus(submission.id, "new")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-blue-700 bg-blue-50 hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors disabled:opacity-50"
                >
                  <RotateCcw className="w-3.5 h-3.5" />
                  Mark as New
                </button>
              )}
              <a
                href={`mailto:${submission.email}?subject=Re: Your inquiry to Alzar FZE`}
                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-teal bg-teal/5 hover:bg-teal/10 border border-teal/20 rounded-lg transition-colors ml-auto"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                Reply via Email
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default function AdminDashboard() {
  const { user, loading: authLoading } = useAuth();
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [expandedId, setExpandedId] = useState<number | null>(null);

  // Set noindex for admin page
  useEffect(() => {
    document.title = "Admin Dashboard | Alzar FZE";
    let meta = document.querySelector('meta[name="robots"]') as HTMLMetaElement | null;
    const original = meta?.content;
    if (meta) meta.content = "noindex, nofollow";
    return () => { if (meta && original) meta.content = original; };
  }, []);

  const statsQuery = trpc.admin.submissions.stats.useQuery(undefined, {
    enabled: !!user && user.role === "admin",
    refetchInterval: 30000, // Refresh every 30 seconds
  });

  const submissionsQuery = trpc.admin.submissions.list.useQuery(
    { status: statusFilter === "all" ? undefined : statusFilter, limit: 50 },
    {
      enabled: !!user && user.role === "admin",
      refetchInterval: 30000,
    }
  );

  const updateStatusMutation = trpc.admin.submissions.updateStatus.useMutation({
    onSuccess: () => {
      submissionsQuery.refetch();
      statsQuery.refetch();
      toast.success("Status updated successfully");
    },
    onError: (error) => {
      toast.error(error.message || "Failed to update status");
    },
  });

  const handleUpdateStatus = (id: number, status: "new" | "read" | "replied" | "archived") => {
    updateStatusMutation.mutate({ id, status });
  };

  // Auth loading state
  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-warm-white">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 text-teal animate-spin" />
          <p className="text-navy/50 font-medium">Loading...</p>
        </div>
      </div>
    );
  }

  // Not logged in
  if (!user) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-warm-white">
        <div className="text-center max-w-md p-8">
          <ShieldAlert className="w-12 h-12 text-navy/30 mx-auto mb-4" />
          <h1 className="font-heading font-bold text-2xl text-navy mb-2">Authentication Required</h1>
          <p className="text-slate-dark/60 mb-6">Please sign in to access the admin dashboard.</p>
          <a
            href={getLoginUrl()}
            className="inline-flex items-center gap-2 bg-teal text-white px-6 py-3 rounded-lg font-semibold hover:bg-teal-dark transition-colors"
          >
            Sign In
          </a>
        </div>
      </div>
    );
  }

  // Not admin
  if (user.role !== "admin") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-warm-white">
        <div className="text-center max-w-md p-8">
          <ShieldAlert className="w-12 h-12 text-destructive/50 mx-auto mb-4" />
          <h1 className="font-heading font-bold text-2xl text-navy mb-2">Access Denied</h1>
          <p className="text-slate-dark/60 mb-6">You do not have permission to access this page. Admin privileges are required.</p>
          <Link href="/" className="inline-flex items-center gap-2 text-teal hover:text-teal-dark font-medium transition-colors">
            <ArrowLeft className="w-4 h-4" />
            Return to Homepage
          </Link>
        </div>
      </div>
    );
  }

  const stats = statsQuery.data;
  const submissions = submissionsQuery.data ?? [];

  const filterTabs: { value: StatusFilter; label: string; count?: number }[] = [
    { value: "all", label: "All", count: stats?.total },
    { value: "new", label: "New", count: stats?.new },
    { value: "read", label: "Read", count: stats?.read },
    { value: "replied", label: "Replied", count: stats?.replied },
    { value: "archived", label: "Archived", count: stats?.archived },
  ];

  return (
    <div className="min-h-screen bg-warm-white">
      {/* Header */}
      <header className="bg-navy text-white">
        <div className="container py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/" className="flex items-center gap-2 text-white/60 hover:text-white transition-colors">
              <ArrowLeft className="w-4 h-4" />
              <span className="text-sm">Back to Site</span>
            </Link>
            <div className="w-px h-6 bg-white/20" />
            <h1 className="font-heading font-bold text-lg">Contact Submissions</h1>
          </div>
          <div className="flex items-center gap-3">
            <span className="text-sm text-white/60">{user.name || user.email}</span>
            <div className="w-8 h-8 bg-teal/20 rounded-full flex items-center justify-center text-teal font-semibold text-sm">
              {(user.name || "A").charAt(0).toUpperCase()}
            </div>
          </div>
        </div>
      </header>

      <div className="container py-8">
        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
            <StatCard label="Total Submissions" value={stats.total} icon={MessageSquare} color="bg-navy/5 text-navy" />
            <StatCard label="New" value={stats.new} icon={Inbox} color="bg-blue-50 text-blue-600" />
            <StatCard label="Read" value={stats.read} icon={Eye} color="bg-amber-50 text-amber-600" />
            <StatCard label="Replied" value={stats.replied} icon={CheckCircle2} color="bg-green-50 text-green-600" />
            <StatCard label="Archived" value={stats.archived} icon={Archive} color="bg-gray-50 text-gray-500" />
          </div>
        )}

        {/* Filter tabs */}
        <div className="flex items-center gap-1 mb-6 bg-white rounded-xl border border-navy/5 p-1.5 shadow-sm overflow-x-auto">
          {filterTabs.map((tab) => (
            <button
              key={tab.value}
              onClick={() => setStatusFilter(tab.value)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap ${
                statusFilter === tab.value
                  ? "bg-teal text-white shadow-sm"
                  : "text-navy/60 hover:text-navy hover:bg-navy/5"
              }`}
            >
              {tab.label}
              {tab.count !== undefined && (
                <span className={`text-xs px-1.5 py-0.5 rounded-full ${
                  statusFilter === tab.value ? "bg-white/20" : "bg-navy/5"
                }`}>
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </div>

        {/* Submissions list */}
        {submissionsQuery.isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-6 h-6 text-teal animate-spin" />
          </div>
        ) : submissions.length === 0 ? (
          <div className="text-center py-16 bg-white rounded-xl border border-navy/5">
            <Inbox className="w-12 h-12 text-navy/15 mx-auto mb-4" />
            <h3 className="font-heading font-semibold text-navy/50 text-lg mb-1">No submissions found</h3>
            <p className="text-slate-dark/40 text-sm">
              {statusFilter === "all"
                ? "Contact form submissions will appear here."
                : `No ${statusFilter} submissions at the moment.`}
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {submissions.map((submission: any) => (
              <SubmissionRow
                key={submission.id}
                submission={submission}
                expanded={expandedId === submission.id}
                onToggle={() => setExpandedId(expandedId === submission.id ? null : submission.id)}
                onUpdateStatus={handleUpdateStatus}
                isUpdating={updateStatusMutation.isPending}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
