"use client"

import type React from "react"
import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Mail, ArrowRight, ArrowLeft, Check, AlertCircle } from "lucide-react"
import { resetPasswordRequest, resetPasswordValidate, resetPassword } from "@/services/users/login"

type Step = "email" | "code" | "password" | "success"

export default function FirstTimeLoginPage() {
  const [currentStep, setCurrentStep] = useState<Step>("email")
  const [email, setEmail] = useState("")
  const [code, setCode] = useState(["", "", "", "", "", "", ""])
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")

  // Handle email submission
  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError("")

    try {
      await resetPasswordRequest(email)
      setCurrentStep("code")
    } catch (err: any) {
      setError(err.message || "Failed to send verification code. Please try again.")
    } finally {
      setIsLoading(false)
    }
  }

  // Handle code input
  const handleCodeChange = (index: number, value: string) => {
    if (value.length > 1) return // Only allow single character

    const newCode = [...code]
    newCode[index] = value.toUpperCase()
    setCode(newCode)

    // Auto-focus next input
    if (value && index < 6) {
      const nextInput = document.getElementById(`code-${index + 1}`)
      nextInput?.focus()
    }
  }

  // Handle backspace in code inputs
  const handleCodeKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === "Backspace" && !code[index] && index > 0) {
      const prevInput = document.getElementById(`code-${index - 1}`)
      prevInput?.focus()
    }
  }

  // Handle code validation
  const handleCodeSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const codeString = code.join("")

    if (codeString.length !== 7) {
      setError("Please enter the complete 7-character code.")
      return
    }

    setIsLoading(true)
    setError("")

    try {
      await resetPasswordValidate(email, codeString)
      setCurrentStep("password")
    } catch (err: any) {
      setError(err.message || "Invalid code. Please check and try again.")
    } finally {
      setIsLoading(false)
    }
  }

  // Handle password setup
  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (password !== confirmPassword) {
      setError("Passwords do not match.")
      return
    }

    if (password.length < 8) {
      setError("Password must be at least 8 characters long.")
      return
    }

    setIsLoading(true)
    setError("")

    try {
      const codeString = code.join("")
      await resetPassword(email, codeString, password, confirmPassword)
      setCurrentStep("success")
    } catch (err: any) {
      setError(err.message || "Failed to setup password. Please try again.")
    } finally {
      setIsLoading(false)
    }
  }

  // Reset to email step
  const handleBackToEmail = () => {
    setCurrentStep("email")
    setCode(["", "", "", "", "", "", ""])
    setError("")
  }

  // Resend code
  const handleResendCode = async () => {
    setIsLoading(true)
    setError("")

    try {
      await resetPasswordRequest(email)
      setError("")
      // Show success message briefly
      setError("New code sent to your email!")
      setTimeout(() => setError(""), 3000)
    } catch (err: any) {
      setError(err.message || "Failed to resend code. Please try again.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header */}
      <header className="bg-white border-b border-gray-200">
        <div className="container mx-auto px-4 py-4 flex justify-between items-center">
          <Link href="/" className="flex items-center">
            <Image
              src="/world-mind-logo.png"
              alt="World Mind Development"
              width={180}
              height={40}
              className="h-8 w-auto"
            />
          </Link>
          <Link href="/auth/login" className="text-sm font-medium text-secondary hover:text-secondary-dark">
            Back to <span className="underline">Login</span>
          </Link>
        </div>
      </header>

      {/* Main Content */}
      <main className="flex-grow flex items-center justify-center p-4 md:p-8">
        <div className="w-full max-w-4xl grid md:grid-cols-2 gap-8">
          {/* Left Column - Message */}
          <div className="hidden md:flex flex-col justify-center space-y-6">
            <div className="space-y-4">
              <h1 className="text-4xl font-bold font-heading text-secondary">
                {currentStep === "email" && "First Time Account Setup"}
                {currentStep === "code" && "Verify Your Email"}
                {currentStep === "password" && "Set Your Password"}
                {currentStep === "success" && "Account Setup Complete"}
              </h1>
              <p className="text-lg text-gray-600">
                {currentStep === "email" &&
                  "To setup your account for the first time login, we need to validate your email address."}
                {currentStep === "code" && "We've sent a 7-character verification code to your email address."}
                {currentStep === "password" && "Create a secure password to complete your account setup."}
                {currentStep === "success" && "Your account has been successfully setup and is ready to use."}
              </p>
            </div>

            {/* Progress Steps */}
            <div className="space-y-4">
              <div className="flex items-center space-x-4">
                <div
                  className={`h-8 w-8 rounded-full flex items-center justify-center ${
                    currentStep === "email"
                      ? "bg-primary text-secondary"
                      : ["code", "password", "success"].includes(currentStep)
                        ? "bg-green-500 text-white"
                        : "bg-gray-300"
                  }`}
                >
                  {["code", "password", "success"].includes(currentStep) ? <Check className="h-4 w-4" /> : "1"}
                </div>
                <span className={`text-sm ${currentStep === "email" ? "font-medium text-secondary" : "text-gray-600"}`}>
                  Validate Email
                </span>
              </div>

              <div className="flex items-center space-x-4">
                <div
                  className={`h-8 w-8 rounded-full flex items-center justify-center ${
                    currentStep === "code"
                      ? "bg-primary text-secondary"
                      : ["password", "success"].includes(currentStep)
                        ? "bg-green-500 text-white"
                        : "bg-gray-300"
                  }`}
                >
                  {["password", "success"].includes(currentStep) ? <Check className="h-4 w-4" /> : "2"}
                </div>
                <span className={`text-sm ${currentStep === "code" ? "font-medium text-secondary" : "text-gray-600"}`}>
                  Verify Code
                </span>
              </div>

              <div className="flex items-center space-x-4">
                <div
                  className={`h-8 w-8 rounded-full flex items-center justify-center ${
                    currentStep === "password"
                      ? "bg-primary text-secondary"
                      : currentStep === "success"
                        ? "bg-green-500 text-white"
                        : "bg-gray-300"
                  }`}
                >
                  {currentStep === "success" ? <Check className="h-4 w-4" /> : "3"}
                </div>
                <span
                  className={`text-sm ${currentStep === "password" ? "font-medium text-secondary" : "text-gray-600"}`}
                >
                  Set Password
                </span>
              </div>
            </div>
          </div>

          {/* Right Column - Form */}
          <div>
            <Card className="border-0 shadow-lg overflow-hidden">
              <CardHeader className="bg-gradient-to-r from-secondary to-secondary-dark text-white p-6">
                <CardTitle className="text-2xl font-bold text-white">
                  {currentStep === "email" && "First Time Setup"}
                  {currentStep === "code" && "Enter Verification Code"}
                  {currentStep === "password" && "Create Your Password"}
                  {currentStep === "success" && "Welcome!"}
                </CardTitle>
                <CardDescription className="text-white/80">
                  {currentStep === "email" && "Enter your email to begin account setup"}
                  {currentStep === "code" && "Enter the 7-character code sent to your email"}
                  {currentStep === "password" && "Create a secure password for your account"}
                  {currentStep === "success" && "Your account is now ready to use"}
                </CardDescription>
              </CardHeader>

              <CardContent className="p-6">
                {/* Step 1: Email Input */}
                {currentStep === "email" && (
                  <form onSubmit={handleEmailSubmit} className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="email" className="text-gray-700">
                        Email Address
                      </Label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                        <Input
                          id="email"
                          type="email"
                          placeholder="you@example.com"
                          value={email}
                          onChange={(e) => setEmail(e.target.value)}
                          className="pl-10 border-gray-300 focus:border-secondary focus:ring-secondary"
                          required
                        />
                      </div>
                      <p className="text-xs text-gray-500">
                        We'll send a verification code to validate your email address
                      </p>
                    </div>

                    {error && (
                      <div className="bg-red-50 border border-red-200 rounded-md p-3 flex items-start space-x-2">
                        <AlertCircle className="h-4 w-4 text-red-500 mt-0.5 flex-shrink-0" />
                        <span className="text-red-700 text-sm">{error}</span>
                      </div>
                    )}

                    <Button
                      type="submit"
                      className="w-full bg-primary hover:bg-primary-medium text-secondary font-medium"
                      disabled={isLoading}
                    >
                      {isLoading ? (
                        <span className="flex items-center justify-center">
                          <svg
                            className="animate-spin -ml-1 mr-2 h-4 w-4 text-secondary"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                          >
                            <circle
                              className="opacity-25"
                              cx="12"
                              cy="12"
                              r="10"
                              stroke="currentColor"
                              strokeWidth="4"
                            ></circle>
                            <path
                              className="opacity-75"
                              fill="currentColor"
                              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                            ></path>
                          </svg>
                          Sending Code...
                        </span>
                      ) : (
                        <span className="flex items-center justify-center">
                          Send Verification Code <ArrowRight className="ml-2 h-4 w-4" />
                        </span>
                      )}
                    </Button>
                  </form>
                )}

                {/* Step 2: Code Input */}
                {currentStep === "code" && (
                  <div className="space-y-6">
                    {/* Email Sent Confirmation */}
                    <div className="bg-green-50 border border-green-200 rounded-md p-4">
                      <div className="flex items-start space-x-3">
                        <Check className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                        <div>
                          <h3 className="text-sm font-medium text-green-800">Verification code sent!</h3>
                          <p className="text-sm text-green-700 mt-1">
                            We've sent a 7-character verification code to <strong>{email}</strong>
                          </p>
                        </div>
                      </div>
                    </div>

                    <form onSubmit={handleCodeSubmit} className="space-y-4">
                      <div className="space-y-2">
                        <Label className="text-gray-700">Verification Code</Label>
                        <div className="flex justify-center space-x-2">
                          {code.map((digit, index) => (
                            <Input
                              key={index}
                              id={`code-${index}`}
                              type="text"
                              maxLength={1}
                              value={digit}
                              onChange={(e) => handleCodeChange(index, e.target.value)}
                              onKeyDown={(e) => handleCodeKeyDown(index, e)}
                              className="w-12 h-12 text-center text-lg font-mono border-gray-300 focus:border-secondary focus:ring-secondary"
                              placeholder="•"
                            />
                          ))}
                        </div>
                      </div>

                      {error && (
                        <div
                          className={`border rounded-md p-3 flex items-start space-x-2 ${
                            error.includes("sent") ? "bg-green-50 border-green-200" : "bg-red-50 border-red-200"
                          }`}
                        >
                          {error.includes("sent") ? (
                            <Check className="h-4 w-4 text-green-500 mt-0.5 flex-shrink-0" />
                          ) : (
                            <AlertCircle className="h-4 w-4 text-red-500 mt-0.5 flex-shrink-0" />
                          )}
                          <span className={`text-sm ${error.includes("sent") ? "text-green-700" : "text-red-700"}`}>
                            {error}
                          </span>
                        </div>
                      )}

                      <Button
                        type="submit"
                        className="w-full bg-primary hover:bg-primary-medium text-secondary font-medium"
                        disabled={isLoading || code.join("").length !== 7}
                      >
                        {isLoading ? (
                          <span className="flex items-center justify-center">
                            <svg
                              className="animate-spin -ml-1 mr-2 h-4 w-4 text-secondary"
                              xmlns="http://www.w3.org/2000/svg"
                              fill="none"
                              viewBox="0 0 24 24"
                            >
                              <circle
                                className="opacity-25"
                                cx="12"
                                cy="12"
                                r="10"
                                stroke="currentColor"
                                strokeWidth="4"
                              ></circle>
                              <path
                                className="opacity-75"
                                fill="currentColor"
                                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                              ></path>
                            </svg>
                            Validating...
                          </span>
                        ) : (
                          "Validate Code"
                        )}
                      </Button>

                      <div className="flex flex-col space-y-2">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={handleResendCode}
                          disabled={isLoading}
                          className="w-full border-gray-300 hover:bg-gray-50"
                        >
                          Resend Code
                        </Button>

                        <Button
                          type="button"
                          variant="ghost"
                          onClick={handleBackToEmail}
                          className="w-full text-gray-600 hover:text-gray-800"
                        >
                          <ArrowLeft className="mr-2 h-4 w-4" />
                          Use Different Email
                        </Button>
                      </div>
                    </form>
                  </div>
                )}

                {/* Step 3: Password Setup */}
                {currentStep === "password" && (
                  <form onSubmit={handlePasswordSubmit} className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="password" className="text-gray-700">
                        Create Password
                      </Label>
                      <Input
                        id="password"
                        type="password"
                        placeholder="Enter your password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        className="border-gray-300 focus:border-secondary focus:ring-secondary"
                        required
                        minLength={8}
                      />
                      <p className="text-xs text-gray-500">Password must be at least 8 characters long</p>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="confirmPassword" className="text-gray-700">
                        Confirm Password
                      </Label>
                      <Input
                        id="confirmPassword"
                        type="password"
                        placeholder="Confirm your password"
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        className="border-gray-300 focus:border-secondary focus:ring-secondary"
                        required
                        minLength={8}
                      />
                    </div>

                    {error && (
                      <div className="bg-red-50 border border-red-200 rounded-md p-3 flex items-start space-x-2">
                        <AlertCircle className="h-4 w-4 text-red-500 mt-0.5 flex-shrink-0" />
                        <span className="text-red-700 text-sm">{error}</span>
                      </div>
                    )}

                    <Button
                      type="submit"
                      className="w-full bg-primary hover:bg-primary-medium text-secondary font-medium"
                      disabled={isLoading || !password || !confirmPassword}
                    >
                      {isLoading ? (
                        <span className="flex items-center justify-center">
                          <svg
                            className="animate-spin -ml-1 mr-2 h-4 w-4 text-secondary"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                          >
                            <circle
                              className="opacity-25"
                              cx="12"
                              cy="12"
                              r="10"
                              stroke="currentColor"
                              strokeWidth="4"
                            ></circle>
                            <path
                              className="opacity-75"
                              fill="currentColor"
                              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                            ></path>
                          </svg>
                          Setting up Account...
                        </span>
                      ) : (
                        "Complete Setup"
                      )}
                    </Button>
                  </form>
                )}

                {/* Step 4: Success */}
                {currentStep === "success" && (
                  <div className="text-center space-y-6">
                    <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                      <Check className="h-8 w-8 text-green-600" />
                    </div>

                    <div className="space-y-2">
                      <h3 className="text-lg font-semibold text-gray-900">Account Setup Complete!</h3>
                      <p className="text-gray-600">
                        Your account has been successfully setup. You can now sign in with your new credentials.
                      </p>
                    </div>

                    <Link href="/auth/login" className="w-full">
                      <Button className="w-full bg-primary hover:bg-primary-medium text-secondary font-medium">
                        Continue to Login
                      </Button>
                    </Link>
                  </div>
                )}
              </CardContent>

              <CardFooter className="p-6 bg-gray-50">
                <div className="w-full text-center text-sm text-gray-500">
                  Already have an account?{" "}
                  <Link href="/auth/login" className="text-secondary hover:text-secondary-dark font-medium">
                    Sign in
                  </Link>
                </div>
              </CardFooter>
            </Card>
          </div>
        </div>
      </main>

      {/* Footer */}
      <footer className="bg-white border-t border-gray-200 py-4">
        <div className="container mx-auto px-4 text-center text-sm text-gray-500">
          © {new Date().getFullYear()} World Mind Development. All rights reserved.
        </div>
      </footer>
    </div>
  )
}
