"use client";

import type React from "react";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Loader2,
  Server,
  MapPin,
  CheckCircle,
  AlertCircle,
  Key,
} from "lucide-react";

// Mock data for locations
const mockLocations = [
  {
    id: "nyc",
    city: "New York",
    country: "United States",
    flag: "🇺🇸",
    region: "North America",
  },
  {
    id: "lon",
    city: "London",
    country: "United Kingdom",
    flag: "🇬🇧",
    region: "Europe",
  },
  {
    id: "fra",
    city: "Frankfurt",
    country: "Germany",
    flag: "🇩🇪",
    region: "Europe",
  },
  {
    id: "sgp",
    city: "Singapore",
    country: "Singapore",
    flag: "🇸🇬",
    region: "Asia Pacific",
  },
  {
    id: "tok",
    city: "Tokyo",
    country: "Japan",
    flag: "🇯🇵",
    region: "Asia Pacific",
  },
  {
    id: "syd",
    city: "Sydney",
    country: "Australia",
    flag: "🇦🇺",
    region: "Asia Pacific",
  },
  {
    id: "tor",
    city: "Toronto",
    country: "Canada",
    flag: "🇨🇦",
    region: "North America",
  },
  {
    id: "ams",
    city: "Amsterdam",
    country: "Netherlands",
    flag: "🇳🇱",
    region: "Europe",
  },
];

type Step = "api-key" | "location-select" | "creating" | "success" | "error";

interface Location {
  id: string;
  city: string;
  country: string;
  flag: string;
  region: string;
}

export default function VPSProvider() {
  const [step, setStep] = useState<Step>("api-key");
  const [apiKey, setApiKey] = useState("");
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(
    null,
  );
  const [error, setError] = useState("");
  const [isValidating, setIsValidating] = useState(false);
  const [isCreating, setIsCreating] = useState(false);

  // Mock API key validation
  const validateApiKey = async (key: string) => {
    setIsValidating(true);
    setError("");

    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // Mock validation - accept keys that are at least 20 characters
    if (key.length >= 20) {
      setStep("location-select");
    } else {
      setError("Invalid API key. Please check your credentials and try again.");
    }

    setIsValidating(false);
  };

  // Mock VPS creation
  const createVPS = async (location: Location) => {
    setIsCreating(true);
    setError("");
    setStep("creating");

    // Simulate VPS creation
    await new Promise((resolve) => setTimeout(resolve, 3000));

    // Mock success/failure (90% success rate)
    if (Math.random() > 0.1) {
      setStep("success");
    } else {
      setError("Failed to create VPS. Please try again or contact support.");
      setStep("error");
    }

    setIsCreating(false);
  };

  const handleApiKeySubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (apiKey.trim()) {
      validateApiKey(apiKey.trim());
    }
  };

  const handleLocationSelect = (location: Location) => {
    setSelectedLocation(location);
    createVPS(location);
  };

  const handleRetry = () => {
    setError("");
    setStep("location-select");
    setSelectedLocation(null);
  };

  const handleNext = () => {
    // This is where the user's flow continues
    console.log("Proceeding to next step...");
  };

  const renderApiKeyStep = () => (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <div className="mx-auto w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-4">
          <Key className="w-6 h-4 text-blue-600" />
        </div>
        <CardTitle>Connect Your Account</CardTitle>
        <CardDescription>
          Enter your API key to get started with VPS deployment
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleApiKeySubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="apiKey">API Key</Label>
            <Input
              id="apiKey"
              type="password"
              placeholder="Enter your API key..."
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              disabled={isValidating}
            />
          </div>

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={!apiKey.trim() || isValidating}
          >
            {isValidating ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Validating...
              </>
            ) : (
              "Validate API Key"
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  );

  const renderLocationSelect = () => (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader className="text-center">
        <div className="mx-auto w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-4">
          <MapPin className="w-6 h-6 text-green-600" />
        </div>
        <CardTitle>Choose Server Location</CardTitle>
        <CardDescription>
          Select the location where you want to deploy your VPS
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {mockLocations.map((location) => (
            <Card
              key={location.id}
              className="cursor-pointer hover:shadow-md transition-shadow border-2 hover:border-blue-200"
              onClick={() => handleLocationSelect(location)}
            >
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <span className="text-2xl">{location.flag}</span>
                  <div className="flex-1">
                    <h3 className="font-semibold">{location.city}</h3>
                    <p className="text-sm text-muted-foreground">
                      {location.country}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {location.region}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </CardContent>
    </Card>
  );

  const renderCreating = () => (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <div className="mx-auto w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-4">
          <Loader2 className="w-6 h-6 text-blue-600 animate-spin" />
        </div>
        <CardTitle>Creating Your VPS</CardTitle>
        <CardDescription>
          Setting up your server in {selectedLocation?.city},{" "}
          {selectedLocation?.country}
        </CardDescription>
      </CardHeader>
      <CardContent className="text-center">
        <div className="flex items-center justify-center space-x-2 mb-4">
          <span className="text-2xl">{selectedLocation?.flag}</span>
          <span className="font-medium">{selectedLocation?.city}</span>
        </div>
        <p className="text-sm text-muted-foreground">
          This may take a few minutes. Please don't close this window.
        </p>
      </CardContent>
    </Card>
  );

  const renderSuccess = () => (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <div className="mx-auto w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-4">
          <CheckCircle className="w-6 h-6 text-green-600" />
        </div>
        <CardTitle>VPS Created Successfully!</CardTitle>
        <CardDescription>
          Your server is ready in {selectedLocation?.city},{" "}
          {selectedLocation?.country}
        </CardDescription>
      </CardHeader>
      <CardContent className="text-center space-y-4">
        <div className="flex items-center justify-center space-x-2 mb-4">
          <span className="text-2xl">{selectedLocation?.flag}</span>
          <span className="font-medium">{selectedLocation?.city}</span>
        </div>

        <Alert>
          <Server className="h-4 w-4" />
          <AlertDescription>
            Your VPS is now online and ready to use!
          </AlertDescription>
        </Alert>

        <Button onClick={handleNext} className="w-full">
          Next
        </Button>
      </CardContent>
    </Card>
  );

  const renderError = () => (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <div className="mx-auto w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-4">
          <AlertCircle className="w-6 h-6 text-red-600" />
        </div>
        <CardTitle>Creation Failed</CardTitle>
        <CardDescription>
          We couldn't create your VPS at this time
        </CardDescription>
      </CardHeader>
      <CardContent className="text-center space-y-4">
        {error && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <div className="flex space-x-2">
          <Button variant="outline" onClick={handleRetry} className="flex-1">
            Try Again
          </Button>
          <Button
            variant="outline"
            onClick={() => setStep("api-key")}
            className="flex-1"
          >
            Start Over
          </Button>
        </div>
      </CardContent>
    </Card>
  );

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4">
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            Cloud VPS Deployment
          </h1>
          <p className="text-gray-600">
            Deploy your virtual private server in minutes
          </p>
        </div>

        {step === "api-key" && renderApiKeyStep()}
        {step === "location-select" && renderLocationSelect()}
        {step === "creating" && renderCreating()}
        {step === "success" && renderSuccess()}
        {step === "error" && renderError()}
      </div>
    </div>
  );
}
