import { createFileRoute } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { Loader2, Plus, Star, Trash2, Users, Pencil } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
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 {
  createWorkspace,
  deleteWorkspace,
  listWorkspaces,
  renameWorkspace,
  setDefaultWorkspace,
  type WorkspaceRow,
} from "@/lib/workspaces.functions";

export const Route = createFileRoute("/_authenticated/workspaces")({
  head: () => ({ meta: [{ title: "Workspaces — eBay BOS" }] }),
  component: WorkspacesPage,
});

function WorkspacesPage() {
  const qc = useQueryClient();
  const fetchList = useServerFn(listWorkspaces);
  const create = useServerFn(createWorkspace);
  const rename = useServerFn(renameWorkspace);
  const remove = useServerFn(deleteWorkspace);
  const setDefault = useServerFn(setDefaultWorkspace);

  const workspaces = useQuery({
    queryKey: ["workspaces"],
    queryFn: () => fetchList({ data: undefined as never }),
  });

  const [createOpen, setCreateOpen] = useState(false);
  const [newName, setNewName] = useState("");
  const [editing, setEditing] = useState<WorkspaceRow | null>(null);
  const [editName, setEditName] = useState("");
  const [deleting, setDeleting] = useState<WorkspaceRow | null>(null);

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ["workspaces"] });
    qc.invalidateQueries({ queryKey: ["me"] });
  };

  const createMut = useMutation({
    mutationFn: (name: string) => create({ data: { name } }),
    onSuccess: () => {
      toast.success("Workspace created");
      setCreateOpen(false);
      setNewName("");
      invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const renameMut = useMutation({
    mutationFn: (v: { id: string; name: string }) => rename({ data: v }),
    onSuccess: () => {
      toast.success("Workspace renamed");
      setEditing(null);
      invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => remove({ data: { id } }),
    onSuccess: () => {
      toast.success("Workspace deleted");
      setDeleting(null);
      invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const setDefaultMut = useMutation({
    mutationFn: (id: string) => setDefault({ data: { id } }),
    onSuccess: () => {
      toast.success("Default workspace updated");
      invalidate();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="mx-auto max-w-4xl space-y-6 px-6 py-8">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Workspaces</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Organize your accounts and data into separate workspaces.
          </p>
        </div>
        <Button onClick={() => setCreateOpen(true)}>
          <Plus className="mr-2 h-4 w-4" /> New workspace
        </Button>
      </div>

      {workspaces.isLoading && (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
        </div>
      )}

      {workspaces.data && workspaces.data.length === 0 && (
        <div className="rounded-xl border bg-muted/30 p-8 text-center text-sm text-muted-foreground">
          You don't have any workspaces yet.
        </div>
      )}

      <div className="grid gap-3">
        {workspaces.data?.map((w) => (
          <div
            key={w.id}
            className="flex flex-col gap-3 rounded-xl border bg-card p-4 sm:flex-row sm:items-center sm:justify-between"
          >
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <span className="truncate font-semibold">{w.name}</span>
                {w.is_default && (
                  <Badge variant="secondary" className="gap-1">
                    <Star className="h-3 w-3" /> Default
                  </Badge>
                )}
                <Badge variant="outline">{w.role}</Badge>
              </div>
              <div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
                <span className="truncate">/{w.slug}</span>
                <span className="inline-flex items-center gap-1">
                  <Users className="h-3 w-3" /> {w.member_count}
                </span>
              </div>
            </div>
            <div className="flex flex-wrap gap-2">
              {!w.is_default && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setDefaultMut.mutate(w.id)}
                  disabled={setDefaultMut.isPending}
                >
                  <Star className="mr-1.5 h-3.5 w-3.5" /> Set default
                </Button>
              )}
              {w.role === "owner" && (
                <>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setEditing(w);
                      setEditName(w.name);
                    }}
                  >
                    <Pencil className="mr-1.5 h-3.5 w-3.5" /> Rename
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setDeleting(w)}
                    className="text-destructive hover:text-destructive"
                  >
                    <Trash2 className="mr-1.5 h-3.5 w-3.5" /> Delete
                  </Button>
                </>
              )}
            </div>
          </div>
        ))}
      </div>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create workspace</DialogTitle>
            <DialogDescription>Workspaces isolate your accounts and data.</DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="ws-name">Name</Label>
            <Input
              id="ws-name"
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="Acme Retail"
              autoFocus
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => createMut.mutate(newName.trim())}
              disabled={createMut.isPending || newName.trim().length < 2}
            >
              {createMut.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!editing} onOpenChange={(o) => !o && setEditing(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Rename workspace</DialogTitle>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="ws-edit">Name</Label>
            <Input
              id="ws-edit"
              value={editName}
              onChange={(e) => setEditName(e.target.value)}
              autoFocus
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditing(null)}>
              Cancel
            </Button>
            <Button
              onClick={() =>
                editing && renameMut.mutate({ id: editing.id, name: editName.trim() })
              }
              disabled={renameMut.isPending || editName.trim().length < 2}
            >
              {renameMut.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete workspace?</AlertDialogTitle>
            <AlertDialogDescription>
              This permanently deletes "{deleting?.name}" and all data associated with it. This
              action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleting && deleteMut.mutate(deleting.id)}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteMut.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
