import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { Copy, RefreshCw } from "lucide-react";

export default function DebugAuthPage() {
  const { user, profile } = useAuth();
  const { toast } = useToast();
  const [accessToken, setAccessToken] = useState<string>("");
  const [refreshToken, setRefreshToken] = useState<string>("");

  const fetchTokens = async () => {
    const { data: { session } } = await supabase.auth.getSession();
    if (session) {
      setAccessToken(session.access_token);
      setRefreshToken(session.refresh_token);
    }
  };

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

  const copyToClipboard = (text: string, label: string) => {
    navigator.clipboard.writeText(text);
    toast({
      title: "已复制",
      description: `${label}已复制到剪贴板`,
    });
  };

  const curlCommand = `curl -X POST \\
  'https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/admin-operations' \\
  -H 'Authorization: Bearer ${accessToken}' \\
  -H 'Content-Type: application/json' \\
  -d '{
    "operation": "query-products",
    "params": {
      "limit": 10
    }
  }'`;

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold mb-2">调试工具</h1>
          <p className="text-muted-foreground">
            用于测试和调试的认证信息
          </p>
        </div>

        <Card className="p-6 space-y-4">
          <div>
            <h2 className="text-xl font-semibold mb-4">用户信息</h2>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">用户ID:</span>
                <span className="font-mono">{user?.id}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">邮箱:</span>
                <span>{user?.email}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">角色:</span>
                <span className="font-semibold">{profile?.role || "user"}</span>
              </div>
            </div>
          </div>
        </Card>

        <Card className="p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold">Access Token (JWT)</h2>
            <Button
              variant="outline"
              size="sm"
              onClick={fetchTokens}
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新
            </Button>
          </div>
          <div className="relative">
            <div className="p-4 bg-muted rounded-lg font-mono text-xs break-all max-h-32 overflow-y-auto">
              {accessToken || "正在加载..."}
            </div>
            <Button
              variant="ghost"
              size="sm"
              className="absolute top-2 right-2"
              onClick={() => copyToClipboard(accessToken, "Access Token")}
            >
              <Copy className="w-4 h-4" />
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            此token用于API请求的Authorization header
          </p>
        </Card>

        <Card className="p-6 space-y-4">
          <h2 className="text-xl font-semibold">cURL 测试命令</h2>
          <div className="relative">
            <pre className="p-4 bg-muted rounded-lg text-xs overflow-x-auto">
              {curlCommand}
            </pre>
            <Button
              variant="ghost"
              size="sm"
              className="absolute top-2 right-2"
              onClick={() => copyToClipboard(curlCommand, "cURL命令")}
            >
              <Copy className="w-4 h-4" />
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            可以在终端或Postman中使用此命令测试Edge Function
          </p>
        </Card>

        <Card className="p-6 space-y-4">
          <h2 className="text-xl font-semibold">Postman/Insomnia 配置</h2>
          <div className="space-y-3 text-sm">
            <div>
              <span className="font-semibold">URL:</span>
              <code className="ml-2 px-2 py-1 bg-muted rounded">
                https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/admin-operations
              </code>
            </div>
            <div>
              <span className="font-semibold">Method:</span>
              <code className="ml-2 px-2 py-1 bg-muted rounded">POST</code>
            </div>
            <div>
              <span className="font-semibold">Headers:</span>
              <div className="ml-4 mt-2 space-y-1">
                <div>Authorization: Bearer {accessToken.slice(0, 20)}...</div>
                <div>Content-Type: application/json</div>
              </div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}
