import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { MoreVertical, Plus, RotateCcw } from "lucide-react";
import { usePagesStore } from "@/stores/pagesStore";
import { restartNode } from "@/api/client";
import StatusBadge from "@/components/dashboard/StatusBadge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export default function ComposeView() {
  const { pages, isLoading, fetchPages, deletePage, publishPage, unpublishPage } =
    usePagesStore();
  const navigate = useNavigate();
  const [pageToDelete, setPageToDelete] = useState<string | null>(null);
  const [restarting, setRestarting] = useState(false);

  useEffect(() => {
    fetchPages();
  }, []);

  const handleRestart = async () => {
    setRestarting(true);
    try {
      await restartNode();
      toast.success("NomadNet restarted");
    } catch (e) {
      toast.error(`Restart failed: ${e}`);
    } finally {
      setRestarting(false);
    }
  };

  const handlePublish = async (name: string) => {
    try {
      await publishPage(name);
      toast.success(`"${name}" published`);
    } catch (e) {
      toast.error(`Failed: ${e}`);
    }
  };

  const handleUnpublish = async (name: string) => {
    try {
      await unpublishPage(name);
      toast.success(`"${name}" unpublished`);
    } catch (e) {
      toast.error(`Failed: ${e}`);
    }
  };

  const handleDelete = async () => {
    if (!pageToDelete) return;
    await deletePage(pageToDelete);
    toast.success(`"${pageToDelete}" deleted`);
    setPageToDelete(null);
  };

  if (isLoading)
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground">
        Loading...
      </div>
    );

  return (
    <div>
      <div>
        {/* Header row */}
        <div className="flex items-center px-4 py-2 border-b-2 border-border">
          <h1 className="text-sm font-semibold flex-1">Compose</h1>
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleRestart} disabled={restarting}>
              <RotateCcw className="w-4 h-4 mr-2" />
              Restart
            </Button>
            <Button onClick={() => navigate("/editor/new")}>
              <Plus className="w-4 h-4 mr-2" />
              New Page
            </Button>
          </div>
        </div>

        {/* Table */}
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Title</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Size</TableHead>
              <TableHead className="w-8" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {pages.map((p) => (
              <TableRow
                key={p.name}
                className="cursor-pointer"
                onClick={() => navigate(`/editor/${p.name}`)}
              >
                <TableCell className="font-mono">
                  {p.name}
                  {p.name === "index" && (
                    <span className="ml-2 text-xs text-primary">homepage</span>
                  )}
                </TableCell>
                <TableCell className="text-muted-foreground">
                  {p.title ?? "\u2014"}
                </TableCell>
                <TableCell>
                  <StatusBadge published={p.published} hasSource={p.has_source} />
                </TableCell>
                <TableCell className="text-muted-foreground">
                  {p.size != null ? `${p.size} B` : "\u2014"}
                </TableCell>
                <TableCell className="text-right w-8">
                  <PageActions
                    name={p.name}
                    published={p.published}
                    onPublish={() => handlePublish(p.name)}
                    onUnpublish={() => handleUnpublish(p.name)}
                    onDelete={() => setPageToDelete(p.name)}
                  />
                </TableCell>
              </TableRow>
            ))}
            {pages.length === 0 && (
              <TableRow>
                <TableCell
                  colSpan={5}
                  className="text-center text-muted-foreground py-8"
                >
                  No pages yet. Create one to get started.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <AlertDialog
        open={pageToDelete !== null}
        onOpenChange={(open) => !open && setPageToDelete(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete "{pageToDelete}"?</AlertDialogTitle>
            <AlertDialogDescription>
              This permanently deletes the page and its source. This cannot be
              undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-white hover:bg-destructive/90"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}


/** Per-row action menu for a page. */
function PageActions({
  name,
  published,
  onPublish,
  onUnpublish,
  onDelete,
}: {
  name: string;
  published: boolean;
  onPublish: () => void;
  onUnpublish: () => void;
  onDelete: () => void;
}) {
  const navigate = useNavigate();

  return (
    <Popover>
      <PopoverTrigger
        render={
          <button
            onClick={(e) => e.stopPropagation()}
            className="p-1 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
          >
            <MoreVertical className="w-4 h-4" />
          </button>
        }
      />
      <PopoverContent side="bottom" align="end" sideOffset={4} className="w-36 p-1">
        <button
          onClick={(e) => { e.stopPropagation(); navigate(`/editor/${name}`); }}
          className="w-full text-left px-3 py-1.5 text-xs hover:bg-accent transition-colors cursor-pointer"
        >Edit</button>
        {published ? (
          <button
            onClick={(e) => { e.stopPropagation(); onUnpublish(); }}
            className="w-full text-left px-3 py-1.5 text-xs hover:bg-accent transition-colors cursor-pointer"
          >Unpublish</button>
        ) : (
          <button
            onClick={(e) => { e.stopPropagation(); onPublish(); }}
            className="w-full text-left px-3 py-1.5 text-xs hover:bg-accent transition-colors cursor-pointer"
          >Publish</button>
        )}
        <button
          onClick={(e) => { e.stopPropagation(); onDelete(); }}
          className="w-full text-left px-3 py-1.5 text-xs text-destructive hover:bg-accent transition-colors cursor-pointer"
        >Delete</button>
      </PopoverContent>
    </Popover>
  );
}
