"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { ArrowLeft, ArrowRight, Check, Sparkles, Code2 } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { auth } from "@/lib/firebase/config";
import { toast } from "sonner";

type ProjectType = "scratch" | "existing" | null;

export default function NewProjectPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [step, setStep] = useState(1);
  const [projectName, setProjectName] = useState("");
  const [projectType, setProjectType] = useState<ProjectType>(null);
  const [workspacePath, setWorkspacePath] = useState<string | null>(null);
  
  // Product vision (can skip)
  const [productVision, setProductVision] = useState("");
  
  // Product details
  const [productName, setProductName] = useState("");
  const [isForClient, setIsForClient] = useState<boolean | null>(null);
  const [hasLogo, setHasLogo] = useState<boolean | null>(null);
  const [hasDomain, setHasDomain] = useState<boolean | null>(null);
  const [hasWebsite, setHasWebsite] = useState<boolean | null>(null);
  const [hasGithub, setHasGithub] = useState<boolean | null>(null);
  const [hasChatGPT, setHasChatGPT] = useState<boolean | null>(null);
  
  const [isCheckingSlug, setIsCheckingSlug] = useState(false);
  const [slugAvailable, setSlugAvailable] = useState<boolean | null>(null);

  // Check for workspacePath query parameter
  useEffect(() => {
    const path = searchParams.get('workspacePath');
    if (path) {
      setWorkspacePath(path);
      // Auto-fill project name from workspace path
      const folderName = path.split('/').pop();
      if (folderName && !projectName) {
        setProjectName(folderName.replace(/-/g, ' ').replace(/_/g, ' '));
      }
    }
  }, [searchParams, projectName]);

  const generateSlug = (name: string) => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "");
  };

  const checkSlugAvailability = async (name: string) => {
    const slug = generateSlug(name);
    if (!slug) return;
    
    setIsCheckingSlug(true);
    // TODO: Replace with actual API call
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // Mock check - in reality, check against database
    const isAvailable = !["test", "demo", "admin"].includes(slug);
    setSlugAvailable(isAvailable);
    setIsCheckingSlug(false);
  };

  const handleProductNameChange = (value: string) => {
    setProductName(value);
    setSlugAvailable(null);
    if (value.length > 2) {
      checkSlugAvailability(value);
    }
  };

  const handleNext = () => {
    if (step === 1 && projectName && projectType) {
      setStep(2);
    } else if (step === 2) {
      // Can skip questions
      setStep(3);
    } else if (step === 3 && productName && slugAvailable) {
      handleCreateProject();
    }
  };

  const handleBack = () => {
    if (step > 1) setStep(step - 1);
  };

  const handleSkipQuestions = () => {
    setStep(3);
  };

  const handleCreateProject = async () => {
    const slug = generateSlug(productName);
    
    const projectData = {
      projectName,
      projectType,
      slug,
      vision: productVision,
      product: {
        name: productName,
        isForClient,
        hasLogo,
        hasDomain,
        hasWebsite,
        hasGithub,
        hasChatGPT,
      },
      workspacePath,
    };

    try {
      const user = auth.currentUser;
      if (!user) {
        toast.error('You must be signed in to create a project');
        return;
      }

      const token = await user.getIdToken();
      
      const response = await fetch('/api/projects/create', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(projectData),
      });

      if (response.ok) {
        const data = await response.json();
        toast.success('Project created successfully!');
        // Redirect to AI chat to start with vision questions
        router.push(`/${data.workspace}/project/${data.projectId}/v_ai_chat`);
      } else {
        const error = await response.json();
        toast.error(error.error || 'Failed to create project');
      }
    } catch (error) {
      console.error('Error creating project:', error);
      toast.error('An error occurred while creating project');
    }
  };

  const canProceedStep1 = projectName.trim() && projectType;
  const canProceedStep3 = productName.trim() && slugAvailable;

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-2xl">
        {/* Header */}
        <div className="mb-8">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => router.push("/projects")}
            className="mb-4"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Projects
          </Button>
          <h1 className="text-3xl font-bold">Create New Project</h1>
          <p className="text-muted-foreground mt-2">
            Step {step} of 3
          </p>
        </div>

        {/* Progress */}
        <div className="flex gap-2 mb-8">
          {[1, 2, 3].map((s) => (
            <div
              key={s}
              className={`h-2 flex-1 rounded-full transition-colors ${
                s <= step ? "bg-primary" : "bg-muted"
              }`}
            />
          ))}
        </div>

        {/* Step 1: Project Setup */}
        {step === 1 && (
          <Card>
            <CardHeader>
              <CardTitle>Project Setup</CardTitle>
              <CardDescription>
                Give your project a name and choose how you want to start
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="projectName">Project Name</Label>
                <Input
                  id="projectName"
                  placeholder="My Awesome Project"
                  value={projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                />
              </div>

              <div className="space-y-3">
                <Label>Starting Point</Label>
                <div className="grid gap-3">
                  <button
                    onClick={() => setProjectType("scratch")}
                    className={`text-left p-4 rounded-lg border-2 transition-colors ${
                      projectType === "scratch"
                        ? "border-primary bg-primary/5"
                        : "border-border hover:border-primary/50"
                    }`}
                  >
                    <div className="flex items-start gap-3">
                      <Sparkles className="h-5 w-5 mt-0.5 text-primary" />
                      <div>
                        <div className="font-medium">Start from scratch</div>
                        <div className="text-sm text-muted-foreground">
                          Build a new project with AI assistance
                        </div>
                      </div>
                      {projectType === "scratch" && (
                        <Check className="h-5 w-5 ml-auto text-primary" />
                      )}
                    </div>
                  </button>

                  <button
                    onClick={() => setProjectType("existing")}
                    className={`text-left p-4 rounded-lg border-2 transition-colors ${
                      projectType === "existing"
                        ? "border-primary bg-primary/5"
                        : "border-border hover:border-primary/50"
                    }`}
                  >
                    <div className="flex items-start gap-3">
                      <Code2 className="h-5 w-5 mt-0.5 text-primary" />
                      <div>
                        <div className="font-medium">Existing project</div>
                        <div className="text-sm text-muted-foreground">
                          Import and enhance an existing codebase
                        </div>
                      </div>
                      {projectType === "existing" && (
                        <Check className="h-5 w-5 ml-auto text-primary" />
                      )}
                    </div>
                  </button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Step 2: Product Vision */}
        {step === 2 && (
          <Card>
            <CardHeader>
              <CardTitle>Describe your product vision</CardTitle>
              <CardDescription>
                Help us understand your project (you can skip this)
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <Textarea
                  placeholder="Describe who you're building for, what problem they have, and how you plan to solve it..."
                  value={productVision}
                  onChange={(e) => setProductVision(e.target.value)}
                  rows={8}
                  className="resize-none"
                />
              </div>

              <Button
                variant="ghost"
                className="w-full"
                onClick={handleSkipQuestions}
              >
                Skip this step
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Step 3: Product Details */}
        {step === 3 && (
          <Card>
            <CardHeader>
              <CardTitle>Product Details</CardTitle>
              <CardDescription>
                Tell us about your product
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="productName">Product Name *</Label>
                <Input
                  id="productName"
                  placeholder="Taskify"
                  value={productName}
                  onChange={(e) => handleProductNameChange(e.target.value)}
                />
                {productName && (
                  <div className="text-xs text-muted-foreground">
                    {isCheckingSlug ? (
                      <span>Checking availability...</span>
                    ) : slugAvailable === true ? (
                      <span className="text-green-600">
                        ✓ URL available: vibn.app/{generateSlug(productName)}
                      </span>
                    ) : slugAvailable === false ? (
                      <span className="text-red-600">
                        ✗ This name is already taken
                      </span>
                    ) : null}
                  </div>
                )}
              </div>

              <div className="space-y-4">
                {/* Client or Self */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Is this for a client or yourself?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={isForClient === true ? "default" : "outline"}
                      onClick={() => setIsForClient(true)}
                      size="sm"
                      className="w-20 h-8"
                    >
                      Client
                    </Button>
                    <Button
                      type="button"
                      variant={isForClient === false ? "default" : "outline"}
                      onClick={() => setIsForClient(false)}
                      size="sm"
                      className="w-20 h-8"
                    >
                      Myself
                    </Button>
                  </div>
                </div>

                {/* Logo */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Does it have a logo?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={hasLogo === true ? "default" : "outline"}
                      onClick={() => setHasLogo(true)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      Yes
                    </Button>
                    <Button
                      type="button"
                      variant={hasLogo === false ? "default" : "outline"}
                      onClick={() => setHasLogo(false)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      No
                    </Button>
                  </div>
                </div>

                {/* Domain */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Does it have a domain?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={hasDomain === true ? "default" : "outline"}
                      onClick={() => setHasDomain(true)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      Yes
                    </Button>
                    <Button
                      type="button"
                      variant={hasDomain === false ? "default" : "outline"}
                      onClick={() => setHasDomain(false)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      No
                    </Button>
                  </div>
                </div>

                {/* Website */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Does it have a website?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={hasWebsite === true ? "default" : "outline"}
                      onClick={() => setHasWebsite(true)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      Yes
                    </Button>
                    <Button
                      type="button"
                      variant={hasWebsite === false ? "default" : "outline"}
                      onClick={() => setHasWebsite(false)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      No
                    </Button>
                  </div>
                </div>

                {/* GitHub */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Do you have a GitHub repository?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={hasGithub === true ? "default" : "outline"}
                      onClick={() => setHasGithub(true)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      Yes
                    </Button>
                    <Button
                      type="button"
                      variant={hasGithub === false ? "default" : "outline"}
                      onClick={() => setHasGithub(false)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      No
                    </Button>
                  </div>
                </div>

                {/* ChatGPT */}
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-normal">Do you have your ideas in a ChatGPT project?</Label>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={hasChatGPT === true ? "default" : "outline"}
                      onClick={() => setHasChatGPT(true)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      Yes
                    </Button>
                    <Button
                      type="button"
                      variant={hasChatGPT === false ? "default" : "outline"}
                      onClick={() => setHasChatGPT(false)}
                      size="sm"
                      className="w-16 h-8"
                    >
                      No
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Navigation */}
        <div className="flex gap-3 mt-6">
          {step > 1 && (
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back
            </Button>
          )}
          <Button
            className="ml-auto"
            onClick={handleNext}
            disabled={
              (step === 1 && !canProceedStep1) ||
              (step === 3 && !canProceedStep3) ||
              isCheckingSlug
            }
          >
            {step === 3 ? "Create Project" : "Next"}
            {step < 3 && <ArrowRight className="h-4 w-4 ml-2" />}
          </Button>
        </div>
      </div>
    </div>
  );
}

