import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { BenchmarkTable } from "@/components/BenchmarkTable";
import { mirrors } from "@/config/mirrors";
import { benchmarkAllMirrors } from "@/utils/benchmark";
import { BenchmarkResult } from "@/types/benchmark";
import { toast } from "sonner";
import { Activity, Zap } from "lucide-react";

const Index = () => {
  const [did, setDid] = useState("");
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<BenchmarkResult[]>([]);

  const resolveHandle = async (handle: string): Promise<string | null> => {
    try {
      const response = await fetch(
        `https://quickdid.smokesignal.tools/xrpc/com.atproto.identity.resolveHandle?handle=${
          encodeURIComponent(handle)
        }`,
      );
      const data = await response.json();

      if (data.error) {
        toast.error(
          `Unable to resolve handle: ${data.message || "Invalid handle"}`,
        );
        return null;
      }

      return data.did;
    } catch (error) {
      toast.error("Failed to resolve handle");
      console.error(error);
      return null;
    }
  };

  const handleBenchmark = async () => {
    if (!did.trim()) {
      toast.error("Please enter a DID or handle");
      return;
    }

    setLoading(true);
    setResults([]);

    try {
      let resolvedDid = did.trim();

      // If input doesn't start with "did:plc", treat it as a handle
      if (!resolvedDid.startsWith("did:plc")) {
        const resolved = await resolveHandle(resolvedDid);
        if (!resolved) {
          setLoading(false);
          return;
        }
        resolvedDid = resolved;
        toast.success(`Resolved to ${resolvedDid}`);
      }

      const benchmarkResults = await benchmarkAllMirrors(mirrors, resolvedDid);
      setResults(benchmarkResults);

      const successCount = benchmarkResults.filter((r) =>
        r.status === "success"
      ).length;
      toast.success(
        `Benchmark complete! ${successCount}/${benchmarkResults.length} mirrors responded`,
      );
    } catch (error) {
      toast.error("Failed to run benchmark");
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !loading) {
      handleBenchmark();
    }
  };

  return (
    <div className="min-h-screen bg-background py-8 px-4">
      <div className="max-w-6xl mx-auto space-y-8">
        {/* Header */}
        <header className="text-center space-y-3">
          <div className="flex items-center justify-center gap-2 text-primary">
            <Activity className="w-8 h-8" />
            <h1 className="text-4xl font-bold">PLC Mirror Benchmark</h1>
          </div>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
            Test and compare response times across different PLC.directory
            mirrors
          </p>
        </header>

        {/* Input Section */}
        <div className="bg-card border border-border rounded-lg p-6 shadow-sm">
          <div className="space-y-4">
            <div>
              <label
                htmlFor="did-input"
                className="block text-sm font-medium mb-2"
              >
                ATProto DID or Handle
              </label>
              <div className="flex gap-3">
                <Input
                  id="did-input"
                  type="text"
                  placeholder="did:plc:example123... or handle.bsky.social"
                  value={did}
                  onChange={(e) => setDid(e.target.value)}
                  onKeyPress={handleKeyPress}
                  className="flex-1 font-mono"
                  disabled={loading}
                />
                <Button
                  onClick={handleBenchmark}
                  disabled={loading || !did.trim()}
                  className="gap-2"
                >
                  <Zap className="w-4 h-4" />
                  {loading ? "Benchmarking..." : "Run Benchmark"}
                </Button>
              </div>
            </div>
            <div className="text-sm text-muted-foreground">
              Testing {mirrors.length} mirrors with 5 attempts each
            </div>
          </div>
        </div>

        {/* Results Section */}
        {(results.length > 0 || loading) && (
          <div className="space-y-4">
            <h2 className="text-2xl font-semibold">Results</h2>
            {loading
              ? (
                <div className="bg-card border border-border rounded-lg p-12 text-center">
                  <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4">
                  </div>
                  <p className="text-muted-foreground">
                    Benchmarking mirrors...
                  </p>
                </div>
              )
              : <BenchmarkTable results={results} />}
          </div>
        )}

        {/* Info Section */}
        {results.length === 0 && !loading && (
          <div className="bg-muted/30 border border-border rounded-lg p-6">
            <h3 className="font-semibold mb-2">How to use:</h3>
            <ol className="list-decimal list-inside space-y-1 text-sm text-muted-foreground">
              <li>
                Enter an ATProto DID or handle (e.g.,
                did:plc:z72i7hdynmk6r22z27h6tvur or handle.bsky.social)
              </li>
              <li>Click "Run Benchmark" or press Enter</li>
              <li>View response times and status for each mirror</li>
            </ol>
            <div className="mt-4 pt-4 border-t border-border">
              <p className="text-sm text-muted-foreground">
                Mirrors can be configured in{" "}
                <code className="bg-background px-2 py-1 rounded text-mono">
                  src/config/mirrors.ts
                </code>
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Index;
