import React, { useState } from "react";
import { Button } from '../ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "../ui/select";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { Loader2 } from "lucide-react";
import { useToast } from "../ui/toast";

export default function NewDroplet() {
  const { showToast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    region: "",
    size: "",
    image: "",
    backups: false,
    ipv6: true,
    monitoring: false
  });

  const regions = [
    { value: "nyc1", label: "New York 1" },
    { value: "nyc3", label: "New York 3" },
    { value: "sfo3", label: "San Francisco 3" },
    { value: "ams3", label: "Amsterdam 3" },
  ];

  const sizes = [
    { value: "s-1vcpu-1gb", label: "1 vCPU, 1GB RAM" },
    { value: "s-1vcpu-2gb", label: "1 vCPU, 2GB RAM" },
    { value: "s-2vcpu-2gb", label: "2 vCPU, 2GB RAM" },
  ];

  const images = [
    { value: "ubuntu-22-04-x64", label: "Ubuntu 22.04" },
    { value: "ubuntu-20-04-x64", label: "Ubuntu 20.04" },
    { value: "debian-11-x64", label: "Debian 11" },
  ];

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSelectChange = (name, value) => {
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const response = await fetch("https://api.digitalocean.com/v2/droplets", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer dop_v1_b6a075ece5786faf7c58d21761dbf95d47af372da062d68a870ce2a0bae51adf"
        },
        body: JSON.stringify({
          ...formData,
          ssh_keys: [47441478]
        })
      });

      const data = await response.json();

      if (response.ok) {
        showToast(`Droplet ${formData.name} created successfully!`, { type: 'success' });
        // Reset form
        setFormData({
          name: "",
          region: "nyc3",
          size: "s-1vcpu-1gb",
          image: "ubuntu-22-04-x64",
          backups: false,
          ipv6: true,
          monitoring: false
        });
      } else {
        throw new Error(data.message || "Failed to create droplet");
      }
    } catch (error) {
      showToast(error.message, { type: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className="max-w-xl mx-auto px-4 my-4">
      <CardHeader>
        <CardTitle>Create New Droplet</CardTitle>
        <CardDescription>Configure your new cloud server</CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">Droplet Name</Label>
            <Input
              id="name"
              name="name"
              type="text"
              placeholder="my-droplet"
              value={formData.name}
              onChange={handleChange}
              required
            />
          </div>

          <div className="space-y-2">
            <Label>Region</Label>
            <Select
              value={formData.region}
              onValueChange={(value) => handleSelectChange("region", value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select region" />
              </SelectTrigger>
              <SelectContent>
                {regions.map(region => (
                  <SelectItem key={region.value} value={region.value}>
                    {region.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>Size</Label>
            <Select
              value={formData.size}
              onValueChange={(value) => handleSelectChange("size", value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select size" />
              </SelectTrigger>
              <SelectContent>
                {sizes.map(size => (
                  <SelectItem key={size.value} value={size.value}>
                    {size.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>Image</Label>
            <Select
              value={formData.image}
              onValueChange={(value) => handleSelectChange("image", value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select OS image" />
              </SelectTrigger>
              <SelectContent>
                {images.map(image => (
                  <SelectItem key={image.value} value={image.value}>
                    {image.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="backups"
              name="backups"
              checked={formData.backups}
              onChange={handleChange}
              className="h-4 w-4"
            />
            <Label htmlFor="backups">Enable Backups</Label>
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="ipv6"
              name="ipv6"
              checked={formData.ipv6}
              onChange={handleChange}
              className="h-4 w-4"
            />
            <Label htmlFor="ipv6">Enable IPv6</Label>
          </div>

          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Creating...
              </>
            ) : (
              "Create Droplet"
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}