import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getTelegramSettings, saveTelegramSettings, disconnectTelegram } from "@/lib/admin.functions";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { CheckCircle2 } from "lucide-react";

export const Route = createFileRoute("/admin/settings")({
  component: SettingsPage,
});

function SettingsPage() {
  const getFn = useServerFn(getTelegramSettings);
  const saveFn = useServerFn(saveTelegramSettings);
  const disconnectFn = useServerFn(disconnectTelegram);
  const qc = useQueryClient();
  const { data } = useQuery({ queryKey: ["admin", "telegram"], queryFn: () => getFn() });

  const [token, setToken] = useState("");
  const [chatId, setChatId] = useState("");

  useEffect(() => {
    if (data) setChatId(data.admin_chat_id ?? "");
  }, [data]);

  const save = useMutation({
    mutationFn: () => saveFn({ data: { bot_token: token, admin_chat_id: chatId } }),
    onSuccess: (r: any) => {
      qc.invalidateQueries({ queryKey: ["admin", "telegram"] });
      toast.success(`Connected to @${r.username}`);
      setToken("");
    },
    onError: (e: any) => toast.error(e.message ?? "Failed"),
  });
  const disconnect = useMutation({
    mutationFn: () => disconnectFn(),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admin", "telegram"] }); toast.success("Disconnected"); },
  });

  return (
    <div className="max-w-2xl space-y-6">
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-semibold">Telegram Bot Connection</h2>
          {data?.is_enabled && (
            <span className="flex items-center gap-1 text-xs text-green-600 font-medium">
              <CheckCircle2 className="w-4 h-4" /> Connected{data.bot_username && ` as @${data.bot_username}`}
            </span>
          )}
        </div>
        <p className="text-sm text-muted-foreground mb-4">
          Get a bot token from <a href="https://t.me/BotFather" target="_blank" rel="noreferrer" className="text-primary hover:underline">@BotFather</a>, send <code>/start</code> to your bot, then use <a href="https://t.me/userinfobot" target="_blank" rel="noreferrer" className="text-primary hover:underline">@userinfobot</a> to get your chat ID.
        </p>
        <div className="space-y-3">
          <div>
            <Label>Bot Token</Label>
            <Input type="password" placeholder={data?.has_token ? "•••••• (set, paste to change)" : "123456:ABC..."} value={token} onChange={(e) => setToken(e.target.value)} />
          </div>
          <div>
            <Label>Admin Chat ID</Label>
            <Input placeholder="123456789" value={chatId} onChange={(e) => setChatId(e.target.value)} />
          </div>
          <div className="flex gap-2">
            <Button onClick={() => save.mutate()} disabled={save.isPending || !token || !chatId}>
              {save.isPending ? "Testing & saving..." : "Save & Test"}
            </Button>
            {data?.is_enabled && (
              <Button variant="outline" onClick={() => disconnect.mutate()} disabled={disconnect.isPending}>Disconnect</Button>
            )}
          </div>
        </div>
      </Card>
    </div>
  );
}