import { useState, useEffect } from "react";
import { useAuth } from "@/_core/hooks/useAuth";
import { useLocation } from "wouter";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import {
  ExternalLink,
  LogOut,
  Loader2,
  Download,
  Copy,
} from "lucide-react";

export default function Admin() {
  const { user, logout, isAuthenticated } = useAuth();
  const [, navigate] = useLocation();
  const [selectedStatus, setSelectedStatus] = useState<string | undefined>();
  const [expandedId, setExpandedId] = useState<number | null>(null);

  // Redirect if not authenticated or not admin
  useEffect(() => {
    if (!isAuthenticated) {
      navigate("/");
      return;
    }
    if (user?.role !== "admin") {
      navigate("/");
    }
  }, [isAuthenticated, user, navigate]);

  const applicationsQuery = trpc.applications.list.useQuery({ status: selectedStatus });
  const countQuery = trpc.applications.getCount.useQuery();
  const updateStatusMutation = trpc.applications.updateStatus.useMutation({
    onSuccess: () => {
      applicationsQuery.refetch();
      toast.success("Application status updated");
    },
    onError: () => {
      toast.error("Failed to update status");
    },
  });

  const handleStatusChange = (id: number, newStatus: "pending" | "approved" | "rejected") => {
    updateStatusMutation.mutate({ id, status: newStatus });
  };

  const exportToCSV = () => {
    if (!applicationsQuery.data || applicationsQuery.data.length === 0) {
      toast.error("No applications to export");
      return;
    }

    const headers = ["Full Name", "Stage Name", "Category", "Location", "Years of Experience", "Instagram", "TikTok", "Video Link", "Past Events", "Status", "Applied Date"];
    const rows = applicationsQuery.data.map((app) => [
      app.fullName,
      app.stageName || "",
      app.category,
      app.location,
      app.yearsOfExperience,
      app.instagramLink || "",
      app.tiktokLink || "",
      app.videoLink || "",
      app.pastEvents || "",
      app.status,
      new Date(app.createdAt).toLocaleDateString(),
    ]);

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

    const blob = new Blob([csv], { type: "text/csv" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `vocalclips-applicants-${new Date().toISOString().split("T")[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
    toast.success("Exported to CSV");
  };

  const copyToClipboard = () => {
    if (!applicationsQuery.data || applicationsQuery.data.length === 0) {
      toast.error("No applications to copy");
      return;
    }

    const headers = ["Full Name", "Stage Name", "Category", "Location", "Years of Experience", "Instagram", "TikTok", "Video Link", "Past Events", "Status", "Applied Date"];
    const rows = applicationsQuery.data.map((app) => [
      app.fullName,
      app.stageName || "",
      app.category,
      app.location,
      app.yearsOfExperience,
      app.instagramLink || "",
      app.tiktokLink || "",
      app.videoLink || "",
      app.pastEvents || "",
      app.status,
      new Date(app.createdAt).toLocaleDateString(),
    ]);

    const tsv = [headers, ...rows].map((row) => row.join("\t")).join("\n");

    navigator.clipboard.writeText(tsv).then(() => {
      toast.success("Copied to clipboard! Paste into Excel or Google Sheets");
    }).catch(() => {
      toast.error("Failed to copy to clipboard");
    });
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "approved":
        return (
          <Badge className="bg-green-500/20 text-green-400 border-green-500/30">
            <div className="w-3 h-3 mr-1 inline-block">
              <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M26 32L30 36L40 26" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            Approved
          </Badge>
        );
      case "rejected":
        return (
          <Badge className="bg-red-500/20 text-red-400 border-red-500/30">
            <div className="w-3 h-3 mr-1 inline-block">
              <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M24 24L40 40M40 24L24 40" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
              </svg>
            </div>
            Rejected
          </Badge>
        );
      default:
        return (
          <Badge className="bg-yellow-500/20 text-yellow-400 border-yellow-500/30">
            <div className="w-3 h-3 mr-1 inline-block">
              <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="32" cy="32" r="4" fill="currentColor" />
              </svg>
            </div>
            Pending
          </Badge>
        );
    }
  };

  if (!isAuthenticated || user?.role !== "admin") {
    return null;
  }

  return (
    <div className="min-h-screen bg-background text-foreground">
      {/* Header */}
      <header className="border-b border-border bg-card/50 backdrop-blur-md sticky top-0 z-40">
        <div className="container max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <img 
              src="https://files.manuscdn.com/user_upload_by_module/session_file/310519663273617054/OvdqELJEnlKYsShR.png" 
              alt="Vocalclips Logo" 
              className="h-12 w-auto"
            />
            <div>
              <h1 className="text-2xl font-bold">Applications Dashboard</h1>
              <p className="text-sm text-muted-foreground">Manage talent applications</p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <div className="text-right">
              <p className="text-sm text-muted-foreground">Logged in as</p>
              <p className="font-semibold">{user?.name}</p>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                logout();
                navigate("/");
              }}
              className="border-border hover:bg-card"
            >
              <LogOut className="h-4 w-4 mr-2" />
              Logout
            </Button>
          </div>
        </div>
      </header>

      <main className="container max-w-7xl mx-auto px-4 py-8">
        {/* Stats Cards */}
        <div className="grid md:grid-cols-3 gap-6 mb-8">
          <Card className="bg-card border-border p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground mb-2">Total Applications</p>
                <p className="text-3xl font-bold">{countQuery.data || 0}</p>
              </div>
              <div className="w-8 h-8 text-accent opacity-50">
                <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="20" cy="24" r="5" fill="currentColor" opacity="0.7" />
                  <circle cx="44" cy="24" r="5" fill="currentColor" opacity="0.7" />
                  <circle cx="32" cy="40" r="5" fill="currentColor" opacity="0.7" />
                  <path d="M20 29V35" stroke="currentColor" strokeWidth="1.5" opacity="0.5" />
                  <path d="M44 29V35" stroke="currentColor" strokeWidth="1.5" opacity="0.5" />
                  <path d="M32 45V52" stroke="currentColor" strokeWidth="1.5" opacity="0.5" />
                </svg>
              </div>
            </div>
          </Card>

          <Card className="bg-card border-border p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground mb-2">Founding Spots</p>
                <p className="text-3xl font-bold">
                  {countQuery.data || 0} / 50
                </p>
              </div>
              <div className="w-8 h-8 text-accent opacity-50">
                <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M16 28L32 16L48 28V48H16V28Z" stroke="currentColor" strokeWidth="1.5" fill="currentColor" opacity="0.6" />
                  <path d="M24 48V36H40V48" stroke="currentColor" strokeWidth="1.5" fill="currentColor" opacity="0.4" />
                </svg>
              </div>
            </div>
          </Card>

          <Card className="bg-card border-border p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground mb-2">Spots Remaining</p>
                <p className="text-3xl font-bold text-accent">
                  {Math.max(0, 50 - (countQuery.data || 0))}
                </p>
              </div>
              <div className="w-8 h-8 text-accent opacity-50">
                <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="32" cy="32" r="24" stroke="currentColor" strokeWidth="1.5" fill="none" opacity="0.3" />
                  <path d="M32 16V48M16 32H48" stroke="currentColor" strokeWidth="2" opacity="0.7" />
                </svg>
              </div>
            </div>
          </Card>
        </div>

        {/* Filter & Export */}
        <div className="mb-6 flex gap-4 items-center justify-between flex-wrap">
          <Select value={selectedStatus || "all"} onValueChange={(val) => setSelectedStatus(val === "all" ? undefined : val)}>
            <SelectTrigger className="w-48 bg-input border-border">
              <SelectValue placeholder="Filter by status" />
            </SelectTrigger>
            <SelectContent className="bg-card border-border">
              <SelectItem value="all">All Applications</SelectItem>
              <SelectItem value="pending">Pending</SelectItem>
              <SelectItem value="approved">Approved</SelectItem>
              <SelectItem value="rejected">Rejected</SelectItem>
            </SelectContent>
          </Select>

          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={copyToClipboard}
              className="border-accent/30 text-accent hover:bg-accent/10"
            >
              <Copy className="h-4 w-4 mr-2" />
              Copy to Clipboard
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={exportToCSV}
              className="border-accent/30 text-accent hover:bg-accent/10"
            >
              <Download className="h-4 w-4 mr-2" />
              Export CSV
            </Button>
          </div>
        </div>

        {/* Applications List */}
        <div className="space-y-4">
          {applicationsQuery.isLoading ? (
            <Card className="bg-card border-border p-8 text-center">
              <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4 text-accent" />
              <p className="text-muted-foreground">Loading applications...</p>
            </Card>
          ) : applicationsQuery.data && applicationsQuery.data.length > 0 ? (
            applicationsQuery.data.map((app) => (
              <Card
                key={app.id}
                className="bg-card border-border hover:border-accent/50 transition-all duration-300 p-6"
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="text-lg font-bold">{app.fullName}</h3>
                      {app.stageName && (
                        <span className="text-sm text-muted-foreground">
                          ({app.stageName})
                        </span>
                      )}
                      {getStatusBadge(app.status)}
                    </div>
                    <p className="text-sm text-muted-foreground mb-2">
                      {app.category} • {app.location} • {app.yearsOfExperience} years experience
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Applied: {new Date(app.createdAt).toLocaleDateString()} at{" "}
                      {new Date(app.createdAt).toLocaleTimeString()}
                    </p>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setExpandedId(expandedId === app.id ? null : app.id)}
                    className="text-accent hover:bg-accent/10"
                  >
                    {expandedId === app.id ? "Hide" : "View"} Details
                  </Button>
                </div>

                {/* Expanded Details */}
                {expandedId === app.id && (
                  <div className="border-t border-border pt-4 mt-4 space-y-4">
                    <div className="grid md:grid-cols-2 gap-4">
                      <div>
                        <p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">
                          Contact Information
                        </p>
                        <div className="space-y-2">
                          {app.instagramLink && (
                            <a
                              href={app.instagramLink}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-accent hover:underline text-sm flex items-center gap-1"
                            >
                              Instagram <ExternalLink className="h-3 w-3" />
                            </a>
                          )}
                          {app.tiktokLink && (
                            <a
                              href={app.tiktokLink}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-accent hover:underline text-sm flex items-center gap-1"
                            >
                              TikTok <ExternalLink className="h-3 w-3" />
                            </a>
                          )}
                          {app.videoLink && (
                            <a
                              href={app.videoLink}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-accent hover:underline text-sm flex items-center gap-1"
                            >
                              Video Portfolio <ExternalLink className="h-3 w-3" />
                            </a>
                          )}
                        </div>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">
                          Background
                        </p>
                        <p className="text-sm">{app.pastEvents || "No past events mentioned"}</p>
                      </div>
                    </div>

                    <p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">
                      Update Status
                    </p>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant={app.status === "approved" ? "default" : "outline"}
                        onClick={() => handleStatusChange(app.id, "approved")}
                        disabled={updateStatusMutation.isPending}
                        className={
                          app.status === "approved"
                            ? "bg-green-500/20 text-green-400 border-green-500/30 hover:bg-green-500/30"
                            : ""
                        }
                      >
                        <svg className="h-4 w-4 mr-1 inline" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M26 32L30 36L40 26" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                        Approve
                      </Button>
                      <Button
                        size="sm"
                        variant={app.status === "rejected" ? "default" : "outline"}
                        onClick={() => handleStatusChange(app.id, "rejected")}
                        disabled={updateStatusMutation.isPending}
                        className={
                          app.status === "rejected"
                            ? "bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30"
                            : ""
                        }
                      >
                        <svg className="h-4 w-4 mr-1 inline" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M24 24L40 40M40 24L24 40" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
                        </svg>
                        Reject
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleStatusChange(app.id, "pending")}
                        disabled={updateStatusMutation.isPending}
                      >
                        <svg className="h-4 w-4 mr-1 inline" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <circle cx="32" cy="32" r="4" fill="currentColor" />
                        </svg>
                        Pending
                      </Button>
                    </div>
                  </div>
                )}
              </Card>
            ))
          ) : (
            <Card className="bg-card border-border p-8 text-center">
              <p className="text-muted-foreground">No applications found</p>
            </Card>
          )}
        </div>
      </main>
    </div>
  );
}
