"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useState } from "react";
import { toast } from "sonner";
import { auth } from "@/lib/firebase/config";
import { Link2, CheckCircle2, Copy } from "lucide-react";

interface ProjectLinkerProps {
  projectId: string;
  projectName: string;
}

export function ProjectLinker({ projectId, projectName }: ProjectLinkerProps) {
  const [workspacePath, setWorkspacePath] = useState("");
  const [isLinking, setIsLinking] = useState(false);
  const [isLinked, setIsLinked] = useState(false);

  const handleLink = async () => {
    if (!workspacePath.trim()) {
      toast.error("Please enter a workspace path");
      return;
    }

    try {
      setIsLinking(true);
      const user = auth.currentUser;
      if (!user) {
        toast.error("Not authenticated");
        return;
      }

      const idToken = await user.getIdToken();

      const response = await fetch("/api/extension/link-project", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${idToken}`,
        },
        body: JSON.stringify({
          projectId,
          workspacePath: workspacePath.trim(),
        }),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Failed to link extension");
      }

      setIsLinked(true);
      toast.success("Extension linked successfully!");
    } catch (error) {
      console.error("Failed to link extension:", error);
      toast.error(error instanceof Error ? error.message : "Failed to link extension");
    } finally {
      setIsLinking(false);
    }
  };

  const copyProjectId = () => {
    navigator.clipboard.writeText(projectId);
    toast.success("Project ID copied to clipboard");
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Link2 className="h-5 w-5" />
          Link Browser Extension
        </CardTitle>
        <CardDescription>
          Connect your Cursor Monitor extension to this project so AI chats are automatically
          captured.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {isLinked ? (
          <div className="flex items-center gap-2 text-green-600 bg-green-50 p-4 rounded-lg">
            <CheckCircle2 className="h-5 w-5" />
            <span className="font-medium">Extension linked to {projectName}</span>
          </div>
        ) : (
          <>
            <div className="space-y-2">
              <Label htmlFor="projectId">Project ID</Label>
              <div className="flex gap-2">
                <Input
                  id="projectId"
                  value={projectId}
                  readOnly
                  className="font-mono text-sm"
                />
                <Button
                  variant="outline"
                  size="icon"
                  onClick={copyProjectId}
                  title="Copy project ID"
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                Copy this ID and add it to your Cursor Monitor extension settings.
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="workspacePath">Workspace Path</Label>
              <Input
                id="workspacePath"
                placeholder="/Users/yourname/projects/my-app"
                value={workspacePath}
                onChange={(e) => setWorkspacePath(e.target.value)}
                className="font-mono text-sm"
              />
              <p className="text-xs text-muted-foreground">
                Enter the full path to your Cursor workspace directory.
              </p>
            </div>

            <Button onClick={handleLink} disabled={isLinking} className="w-full">
              {isLinking ? "Linking..." : "Link Extension"}
            </Button>
          </>
        )}

        <div className="text-xs text-muted-foreground space-y-1 pt-2 border-t">
          <p className="font-medium">How it works:</p>
          <ol className="list-decimal list-inside space-y-1">
            <li>Copy the Project ID above</li>
            <li>Open Cursor Monitor extension settings</li>
            <li>Paste the Project ID in the "Vibn Project ID" field</li>
            <li>Enter your workspace path here and click "Link Extension"</li>
            <li>All AI chats from Cursor will now be captured in this project</li>
          </ol>
        </div>
      </CardContent>
    </Card>
  );
}

