import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client, type CreateUserAccessToken } from "@/client";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogClose } from "@/components/ui/dialog";
import { Key, Trash2, Copy } from "lucide-react";

export default function SettingsTokensPage() {
  const qc = useQueryClient();
  const [newTokenName, setNewTokenName] = useState("");
  const [createdToken, setCreatedToken] = useState("");

  const { data: tokens = [], isLoading } = useQuery({
    queryKey: ["user", "access-tokens"],
    queryFn: async () => {
      const res = await client.userListAccessTokens();
      return res.data;
    },
    retry: false,
  });

  const createToken = useMutation({
    mutationFn: async (data: CreateUserAccessToken) => {
      const res = await client.userCreateAccessToken(data);
      return res.data;
    },
    onSuccess: (data) => {
      setCreatedToken(data.token);
      qc.invalidateQueries({ queryKey: ["user", "access-tokens"] });
    },
  });

  const revokeToken = useMutation({
    mutationFn: async (id: number) => {
      await client.userRevokeAccessToken(id);
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["user", "access-tokens"] }),
  });

  const activeTokens = tokens.filter((t) => !t.is_revoked);

  return (
    <div className="px-8 py-10">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-xl font-heading font-bold text-foreground">Access Tokens</h1>
          <p className="mt-1 text-sm text-muted-foreground">Manage personal access tokens for API authentication</p>
        </div>
        <Dialog
          onOpenChange={(open) => {
            if (!open) {
              setNewTokenName("");
              setCreatedToken("");
            }
          }}
        >
          <DialogTrigger render={<Button size="sm">New token</Button>} />
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create access token</DialogTitle>
            </DialogHeader>
            {createdToken ? (
              <div className="space-y-3">
                <p className="text-sm text-foreground font-medium">Token created! Copy it now — it won't be shown again.</p>
                <div className="flex items-center gap-2">
                  <code className="flex-1 rounded-md bg-muted px-3 py-2 font-mono text-xs text-foreground break-all">
                    {createdToken}
                  </code>
                  <Button
                    className="size-8"
                    onClick={() => navigator.clipboard.writeText(createdToken)}
                    size="icon"
                    variant="outline"
                  >
                    <Copy className="size-4" />
                  </Button>
                </div>
                <DialogClose render={<Button variant="outline">Done</Button>} />
              </div>
            ) : (
              <form
                className="space-y-3"
                onSubmit={(e) => {
                  e.preventDefault();
                  createToken.mutate({ name: newTokenName, scopes: ["read"] });
                }}
              >
                <div>
                  <Label>Token name</Label>
                  <Input
                    className="mt-1 h-9"
                    placeholder="e.g. CI pipeline"
                    value={newTokenName}
                    onChange={(e) => setNewTokenName(e.target.value)}
                  />
                </div>
                <Button size="sm" type="submit" disabled={!newTokenName}>Create token</Button>
              </form>
            )}
          </DialogContent>
        </Dialog>
      </div>

      <div className="mt-8">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 2 }).map((_, i) => (
              <div className="h-12 animate-pulse rounded-lg bg-muted" key={i} />
            ))}
          </div>
        ) : activeTokens.length > 0 ? (
          <div className="space-y-3">
            {activeTokens.map((token) => (
              <Card key={token.id}>
                <CardContent className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Key className="size-4 text-muted-foreground" />
                    <div>
                      <p className="font-heading font-medium text-foreground">{token.name}</p>
                      <p className="font-mono text-xs text-muted-foreground">
                        Created {new Date(token.created_at).toLocaleDateString()}
                        {token.expires_at && ` · Expires ${new Date(token.expires_at).toLocaleDateString()}`}
                        · Scopes: {token.scopes.join(", ")}
                      </p>
                    </div>
                  </div>
                  <Button
                    className="size-8 text-destructive hover:text-destructive"
                    onClick={() => revokeToken.mutate(token.id)}
                    size="icon"
                    variant="ghost"
                  >
                    <Trash2 className="size-4" />
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="py-10 text-center">
            <Key className="mx-auto size-6 text-muted-foreground/30" />
            <p className="mt-4 text-sm text-muted-foreground">No active tokens</p>
          </div>
        )}
      </div>
    </div>
  );
}