"use client"

import { useState } from "react"
import { Mail, User, Lock } from "lucide-react"
import ErrorToast from "@/components/Error"
import { useRouter } from "next/navigation"
import useSite from "@/hooks/useSites"
import axios from "axios"
import useNetworks from "@/hooks/useNetworks"
import { Site } from "@/app/types"

export default function SetupPage() {
  const router = useRouter()
  const [step, setStep] = useState(1)

  const [email, setEmail] = useState("")
  const [username, setUsername] = useState("")
  const [name, setName] = useState("")
  const [password, setPassword] = useState("")
  const [passwordConfirm, setPasswordConfirm] = useState("")

  const [siteName, setSiteName] = useState("")
  const [networkName, setNetworkName] = useState("")

  const { addSite } = useSite()
  const { addNetwork } = useNetworks()

  const [error, setError] = useState("")

  const handleNextStep = () => {
    setStep(step + 1)
  }

  const handlePreviousStep = () => {
    setStep(step - 1)
  }

  const handleComplete = async () => {
    if (password !== passwordConfirm) {
      setError("Passwords do not match")
      return
    }
    try {
      // Create user
      await axios.post("/api/user/create", {
        email,
        username,
        name,
        password
      })

      // Create site using the hook
      const siteResult = addSite({
        id: "",
        name: siteName,
        description: "",
        networks: []
      })
      
      // Handle validation errors (returned as strings)
      if (typeof siteResult === "string") {
        setError(siteResult)
        return
      }
      
      // If not a string, it's a Promise - await it
      const site = await siteResult
      
      if (!site || !site.id) {
        setError("Failed to create site")
        return
      }
      
      // Create network using the hook
      const networkResult = addNetwork({
        id: "",
        name: networkName,
        siteId: site.id,
        ipv4Subnet: "",
        ipv6Subnet: "",
        gateway: ""
      })
      
      // Handle validation errors
      if (typeof networkResult === "string") {
        setError(networkResult)
        return
      }
      
      // If not a string, it's a Promise - await it
      const network = await networkResult

      if (!network) {
        setError("Failed to create network")
        return
      }

      // Success - navigate to home
      router.push("/")
    } catch (error: any) {
      console.error("Error in setup:", error)
      setError(typeof error === "string" ? error : error.response?.data?.error || error.message || "An unknown error occurred")
    }
  }
    
  

  return (
    <div>
      <div className="flex flex-col items-center justify-center min-h-screen p-4">
        <div className="bg-base-200 p-6 rounded-lg shadow-lg w-full max-w-3xl">
          <div className="mb-8">
            <ul className="steps steps-vertical lg:steps-horizontal w-full">
              <li className={step >= 1 ? "step step-primary" : "step"}>Create account</li>
              <li className={step >= 2 ? "step step-primary" : "step"}>Create site & network</li>
              <li className={step >= 3 ? "step step-primary" : "step"}>Next Steps</li>
            </ul>
          </div>

          <div className="mt-6 relative">
            <div className="min-h-[400px] flex flex-col justify-between">
              {step === 1 && (
              <div className="space-y-6 flex-1">
                <div className="space-y-2">
                  <h1 className="text-2xl font-bold">Create account</h1>
                  <p className="text-gray-600">Please create an account to get started.</p>
                </div>

                <div className="w-full space-y-4">
                  <fieldset className="fieldset">
                    <legend className="fieldset-legend">Email</legend>
                    <label className="input validator w-full">
                      <Mail className="w-5 h-5 text-gray-500" />
                      <input type="email" placeholder="mail@site.com" required value={email} onChange={(e) => setEmail(e.target.value)} />
                    </label>
                    <div className="validator-hint hidden">Enter valid email address</div>
                  </fieldset>

                  <div className="flex flex-col md:flex-row gap-4 w-full">
                    <fieldset className="fieldset w-full">
                      <legend className="fieldset-legend">Username</legend>
                      <label className="input validator w-full">
                        <User className="w-5 h-5 text-gray-500" />
                        <input type="text" placeholder="username" minLength={3} maxLength={20} required value={username} onChange={(e) => setUsername(e.target.value)} />
                      </label>
                      <div className="validator-hint hidden">Enter valid username</div>
                    </fieldset>

                    <fieldset className="fieldset w-full">
                      <legend className="fieldset-legend">Full Name</legend>
                      <label className="input validator w-full">
                        <User className="w-5 h-5 text-gray-500" />
                        <input type="text" placeholder="Full Name" minLength={3} maxLength={100} required value={name} onChange={(e) => setName(e.target.value)} />
                      </label>
                      <div className="validator-hint hidden">Enter valid full name</div>
                    </fieldset>
                  </div>

                  <div className="divider"></div>

                  <div className="flex flex-col md:flex-row gap-4 w-full">
                    <fieldset className="fieldset w-full">
                      <legend className="fieldset-legend">Password</legend>
                      <label className="input validator w-full">
                        <Lock className="w-5 h-5 text-gray-500" />
                        <input type="password" placeholder="Password" minLength={8} maxLength={100} required value={password} onChange={(e) => setPassword(e.target.value)} />
                      </label>
                      <div className="validator-hint hidden">Enter valid password</div>
                    </fieldset>

                    <fieldset className="fieldset w-full">
                      <legend className="fieldset-legend">Repeat Password</legend>
                      <label className="input validator w-full">
                        <Lock className="w-5 h-5 text-gray-500" />
                        <input type="password" placeholder="Repeat Password" minLength={8} maxLength={100} required value={passwordConfirm} onChange={(e) => setPasswordConfirm(e.target.value)} />
                      </label>
                      <div className="validator-hint hidden">Enter valid repeat password</div>
                    </fieldset>
                  </div>
                </div>

                <div className="pt-4 mt-auto">
                  <button className="btn btn-primary w-full" onClick={handleNextStep}>
                    Next
                  </button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="flex flex-col justify-between min-h-[400px]">
                <div className="space-y-4">
                  <h1 className="text-2xl font-bold">Create site & network</h1>
                  <p className="text-gray-600">Please create a site & network to get started. Don't worry, you can always change it later.</p>
                </div>

                <div className="w-full space-y-4">
                  <fieldset className="fieldset">
                    <legend className="fieldset-legend">Site Name</legend>
                    <label className="input validator w-full">
                      <input type="text" placeholder="e.g. Homelab" minLength={3} maxLength={100} required value={siteName} onChange={(e) => setSiteName(e.target.value)} />
                    </label>
                    <div className="validator-hint hidden">Enter valid site name</div>
                  </fieldset>

                  <fieldset className="fieldset">
                    <legend className="fieldset-legend">Network Name</legend>
                    <label className="input validator w-full">
                      <input type="text" placeholder="e.g. VLAN 1" minLength={3} maxLength={100} required value={networkName} onChange={(e) => setNetworkName(e.target.value)} />
                    </label>
                    <div className="validator-hint hidden">Enter valid network name</div>
                  </fieldset>
                </div>

                <div className="pt-4 flex flex-col sm:flex-row gap-2">
                  <button className="btn btn-outline flex-1" onClick={handlePreviousStep}>
                    Back
                  </button>
                  <button className="btn btn-primary flex-1" onClick={handleNextStep}>Next</button>
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="flex flex-col justify-between min-h-[400px]">
                <div className="space-y-4">
                  <h1 className="text-2xl font-bold">Next Steps</h1>
                  <p className="text-gray-600">Here are some next steps to get you started</p>

                  <div className="space-y-4 py-4">
                    <p>1. Click Complete to finish the setup & create the user</p>
                    <p>2. Create a site with a network</p>
                    <p>3. Add your first server to the network</p>
                    <p>4. Add all your self-hosted applications to the server</p>
                    <p>5. Setup notifications to be notified about any issues</p>
                    <p>6. Leave a star on <a href="https://github.com/crocofied/corecontrol" target="_blank" rel="noopener noreferrer" className="link">GitHub</a> if you like it</p>
                  </div>    
                </div>

                <div className="pt-4 flex flex-col sm:flex-row gap-2">
                  <button className="btn btn-outline flex-1" onClick={handlePreviousStep}>
                    Back
                  </button>
                  <button className="btn btn-primary flex-1" onClick={handleComplete}>Complete</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
    <ErrorToast message={error} show={!!error} onClose={() => setError("")} />
  </div>
  )
}
