"use client";

import * as React from "react";
import { toast } from "sonner";
import {
  ArrowRightLeft,
  Plus,
  Trash2,
  ExternalLink,
  ShieldCheck,
  AlertTriangle,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { FloatingInput } from "@/components/ui/floating-input";
import { fetchWithAdminCache, invalidateAdminCache } from "@/lib/admin/client-cache";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";

interface RedirectItem {
  id: string;
  source: string;
  destination: string;
  method?: 301 | 302 | 307 | 308;
  permanent: boolean;
  createdAt: string;
  createdBy: string;
}

export default function AdminRedirectsPage() {
  const [redirects, setRedirects] = React.useState<RedirectItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [createOpen, setCreateOpen] = React.useState(false);
  const [source, setSource] = React.useState("");
  const [destination, setDestination] = React.useState("");
  const [method, setMethod] = React.useState<"301" | "302" | "307" | "308">("301");
  const [creating, setCreating] = React.useState(false);

  const [toDelete, setToDelete] = React.useState<RedirectItem | null>(null);
  const [deleting, setDeleting] = React.useState(false);

  const fetchRedirects = async (forceFresh = false) => {
    try {
      setLoading(true);
      const data = await fetchWithAdminCache<{ redirects?: RedirectItem[] }>("/api/admin/redirects", {
        tags: ["redirects"],
        forceFresh,
      });
      setRedirects(data.redirects || []);
    } catch (err: any) {
      toast.error(err.message || "Failed to load redirects");
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchRedirects();
  }, []);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!source.trim() || !destination.trim()) {
      toast.error("Source and destination paths are required.");
      return;
    }

    try {
      setCreating(true);
      const res = await fetch("/api/admin/redirects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          source: source.trim(),
          destination: destination.trim(),
          method: parseInt(method, 10),
          permanent: method === "301" || method === "308",
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create redirect");

      toast.success("Redirect rule created!");
      setCreateOpen(false);
      setSource("");
      setDestination("");
      setMethod("301");
      invalidateAdminCache("redirects");
      fetchRedirects(true);
    } catch (err: any) {
      toast.error(err.message || "Creation failed");
    } finally {
      setCreating(false);
    }
  };

  const handleDelete = async () => {
    if (!toDelete) return;
    try {
      setDeleting(true);
      const res = await fetch(`/api/admin/redirects?id=${toDelete.id}`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Failed to delete redirect");

      toast.success("Redirect rule removed!");
      setToDelete(null);
      invalidateAdminCache("redirects");
      fetchRedirects(true);
    } catch (err: any) {
      toast.error(err.message || "Deletion failed");
    } finally {
      setDeleting(false);
    }
  };

  const renderMethodBadge = (r: RedirectItem) => {
    const m = r.method || (r.permanent ? 301 : 302);
    switch (m) {
      case 301:
        return (
          <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 text-[10px] font-mono">
            301 Permanent
          </Badge>
        );
      case 308:
        return (
          <Badge className="bg-purple-50 text-purple-700 border-purple-200 text-[10px] font-mono">
            308 Permanent
          </Badge>
        );
      case 307:
        return (
          <Badge className="bg-cyan-50 text-cyan-700 border-cyan-200 text-[10px] font-mono">
            307 Temporary
          </Badge>
        );
      case 302:
      default:
        return (
          <Badge className="bg-blue-50 text-blue-700 border-blue-200 text-[10px] font-mono">
            302 Temporary
          </Badge>
        );
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
            URL Redirects
          </h1>
          <p className="mt-0.5 text-xs text-neutral-500">
            Manage canonical HTTP redirects (301, 302, 307, 308) to preserve SEO authority and prevent broken links.
          </p>
        </div>

        <Button
          onClick={() => setCreateOpen(true)}
          className="gap-1.5 rounded-xl text-xs font-semibold"
        >
          <Plus className="h-4 w-4" />
          <span>Add Redirect Rule</span>
        </Button>
      </div>

      {/* Redirects Table */}
      <div className="overflow-hidden rounded-2xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="border-b border-neutral-200 bg-neutral-50/75 text-[11px] font-semibold text-neutral-500 uppercase tracking-wider dark:border-neutral-800 dark:bg-neutral-950/50">
              <tr>
                <th className="px-4 py-3">Source URL</th>
                <th className="px-4 py-3">Destination</th>
                <th className="px-4 py-3">HTTP Method</th>
                <th className="px-4 py-3">Created By</th>
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100 dark:divide-neutral-800">
              {loading ? (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-neutral-400">
                    Loading redirects from MongoDB...
                  </td>
                </tr>
              ) : redirects.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-neutral-500">
                    <p className="font-medium">No custom redirects configured</p>
                    <p className="text-xs text-neutral-400 mt-0.5">
                      Redirects are also automatically created when a published article slug changes.
                    </p>
                  </td>
                </tr>
              ) : (
                redirects.map((r) => (
                  <tr
                    key={r.id}
                    className="transition hover:bg-neutral-50/60 dark:hover:bg-neutral-800/40"
                  >
                    <td className="px-4 py-3.5 font-mono text-neutral-900 dark:text-white">
                      {r.source}
                    </td>
                    <td className="px-4 py-3.5 font-mono text-neutral-600 dark:text-neutral-300">
                      {r.destination}
                    </td>
                    <td className="px-4 py-3.5">
                      {renderMethodBadge(r)}
                    </td>
                    <td className="px-4 py-3.5 text-neutral-500">{r.createdBy}</td>
                    <td suppressHydrationWarning className="px-4 py-3.5 text-neutral-500">
                      {new Date(r.createdAt).toLocaleDateString("en-US")}
                    </td>
                    <td className="px-4 py-3.5 text-right">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setToDelete(r)}
                        className="h-8 w-8 p-0 text-red-500 hover:text-red-600"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create Modal */}
      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent className="sm:max-w-md">
          <form onSubmit={handleCreate}>
            <DialogHeader>
              <DialogTitle className="text-base font-bold">Add URL Redirect Rule</DialogTitle>
              <DialogDescription className="text-xs">
                Map an old URL path to a new destination to preserve SEO rank and prevent 404s.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4 text-xs">
              <FloatingInput
                id="redirect-source"
                label="Source Path (Old URL e.g. /blog/old-slug)"
                placeholder="/blog/old-slug"
                value={source}
                onChange={(e) => setSource(e.target.value)}
                className="font-mono text-xs"
                required
              />

              <FloatingInput
                id="redirect-destination"
                label="Destination Path (e.g. /blog/new-slug or https://...)"
                placeholder="/blog/new-slug"
                value={destination}
                onChange={(e) => setDestination(e.target.value)}
                className="font-mono text-xs"
                required
              />

              {/* Method Selector using shadcn Select */}
              <div className="space-y-1.5">
                <label className="text-[11px] font-semibold text-neutral-600 dark:text-neutral-400">
                  HTTP Redirect Method *
                </label>
                <Select
                  value={method}
                  onValueChange={(val: "301" | "302" | "307" | "308") => setMethod(val)}
                >
                  <SelectTrigger className="w-full text-xs">
                    <SelectValue placeholder="Select HTTP Method" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="301" className="text-xs">
                      301 Permanent Redirect (Default — Recommended for SEO)
                    </SelectItem>
                    <SelectItem value="302" className="text-xs">
                      302 Temporary Redirect (Found)
                    </SelectItem>
                    <SelectItem value="307" className="text-xs">
                      307 Temporary Redirect (Preserves HTTP Method)
                    </SelectItem>
                    <SelectItem value="308" className="text-xs">
                      308 Permanent Redirect (Preserves HTTP Method)
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setCreateOpen(false)}
                className="text-xs"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={creating || !source.trim() || !destination.trim()}
                className="text-xs font-semibold"
              >
                {creating ? "Saving Rule..." : "Create Redirect"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Alert Dialog */}
      <AlertDialog open={!!toDelete} onOpenChange={() => setToDelete(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-base font-bold">
              Delete Redirect Rule?
            </AlertDialogTitle>
            <AlertDialogDescription className="text-xs">
              Are you sure you want to delete the redirect from{" "}
              <code className="rounded bg-neutral-100 px-1 py-0.5 font-mono dark:bg-neutral-800">
                {toDelete?.source}
              </code>{" "}
              to{" "}
              <code className="rounded bg-neutral-100 px-1 py-0.5 font-mono dark:bg-neutral-800">
                {toDelete?.destination}
              </code>
              ? Traffic hitting the source path will no longer be redirected.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleting} className="text-xs">
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleting}
              className="bg-red-600 text-xs font-semibold text-white hover:bg-red-700"
            >
              {deleting ? "Deleting..." : "Delete Rule"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
