"use client"

import type React from "react"

import Link from "next/link"
import { Eye, EyeOff, HeartPulse } from "lucide-react"
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 { useState, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"

const loginSchema = z.object({
  email: z.string().email("Invalid email address"),
  password: z.string().min(1, "Password is required"),
})

type LoginFormValues = z.infer<typeof loginSchema>

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const [isForgotMode, setIsForgotMode] = useState(false)
  const [isResetMode, setIsResetMode] = useState(false)
  const [forgotEmail, setForgotEmail] = useState("")
  const [resetCode, setResetCode] = useState("")
  const [newPassword, setNewPassword] = useState("")
  
  const [resendStatus, setResendStatus] = useState<string | null>(null)
  const [unverifiedEmail, setUnverifiedEmail] = useState<string | null>(null)
  
  const searchParams = useSearchParams()
  const { login } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (searchParams.get('verified')) {
      setSuccess("Email verified successfully. You can now log in.")
    }
  }, [searchParams])
  
  const form = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  })

  const onSubmit = async (values: LoginFormValues) => {
    setIsLoading(true)
    setError(null)
    setSuccess(null)
    setResendStatus(null)
    setUnverifiedEmail(null)

    try {
      const data = await fetchApi('auth.php?action=login', {
        method: 'POST',
        body: JSON.stringify(values),
      })

      login(data.user, data.token)
    } catch (err: any) {
      setError(err.message)
      if (err.unverified) {
        setUnverifiedEmail(err.email)
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleResend = async () => {
    if (!unverifiedEmail) return

    setIsLoading(true)
    setError(null)
    setResendStatus(null)

    try {
      await fetchApi('auth.php?action=resend-verification', {
        method: 'POST',
        body: JSON.stringify({ email: unverifiedEmail }),
      })
      setResendStatus("A new verification code has been sent to your email.")
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to resend code')
    } finally {
      setIsLoading(false)
    }
  }

  const handleForgot = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)
    setSuccess(null)

    try {
      const data = await fetchApi('auth.php?action=forgot-password', {
        method: 'POST',
        body: JSON.stringify({ email: forgotEmail }),
      })
      setSuccess(data.message)
      setIsForgotMode(false)
      setIsResetMode(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred')
    } finally {
      setIsLoading(false)
    }
  }

  const handleReset = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)
    setSuccess(null)

    try {
      const data = await fetchApi('auth.php?action=reset-password', {
        method: 'POST',
        body: JSON.stringify({ email: forgotEmail, code: resetCode, password: newPassword }),
      })
      setSuccess(data.message)
      setIsResetMode(false)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Invalid reset code')
    } finally {
      setIsLoading(false)
    }
  }

  if (isForgotMode) {
    return (
      <div className="container relative flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 min-h-[calc(100vh-4rem)] mx-auto">
        <div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
          <div className="absolute inset-0 bg-primary" />
          <div className="relative z-20 flex items-center text-lg font-medium">
            <HeartPulse className="mr-2 h-6 w-6" />
            OncoConnect
          </div>
        </div>
        <div className="p-4 lg:p-8">
          <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
            <Card className="border-none shadow-none sm:shadow-sm sm:border">
              <CardHeader className="space-y-1">
                <CardTitle className="text-2xl text-center">Forgot Password</CardTitle>
                <CardDescription className="text-center">Enter your email to receive a reset code</CardDescription>
              </CardHeader>
              <form onSubmit={handleForgot}>
                <CardContent className="grid gap-4">
                  <div className="grid gap-2">
                    <Label htmlFor="forgot-email">Email</Label>
                    <Input
                      id="forgot-email"
                      type="email"
                      placeholder="m@example.com"
                      value={forgotEmail}
                      onChange={(e) => setForgotEmail(e.target.value)}
                      required
                    />
                  </div>
                  <Button className="w-full" disabled={isLoading}>
                    {isLoading ? "Sending..." : "Send Reset Code"}
                  </Button>
                </CardContent>
              </form>
              <CardFooter>
                <button 
                  onClick={() => setIsForgotMode(false)}
                  className="w-full text-sm text-center text-muted-foreground hover:text-primary"
                >
                  Back to login
                </button>
              </CardFooter>
            </Card>
          </div>
        </div>
      </div>
    )
  }

  if (isResetMode) {
    return (
      <div className="container relative flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 min-h-[calc(100vh-4rem)] mx-auto">
        <div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
          <div className="absolute inset-0 bg-primary" />
          <div className="relative z-20 flex items-center text-lg font-medium">
            <HeartPulse className="mr-2 h-6 w-6" />
            OncoConnect
          </div>
        </div>
        <div className="p-4 lg:p-8">
          <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
            <Card className="border-none shadow-none sm:shadow-sm sm:border">
              <CardHeader className="space-y-1">
                <CardTitle className="text-2xl text-center">Reset Password</CardTitle>
                <CardDescription className="text-center">Enter the code and your new password</CardDescription>
              </CardHeader>
              <form onSubmit={handleReset}>
                <CardContent className="grid gap-4">
                  <div className="grid gap-2">
                    <Label htmlFor="reset-code">Reset Code</Label>
                    <Input
                      id="reset-code"
                      placeholder="ABC123"
                      value={resetCode}
                      onChange={(e) => setResetCode(e.target.value.toUpperCase())}
                      className="text-center font-mono tracking-widest"
                      required
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="new-password">New Password</Label>
                    <Input
                      id="new-password"
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      required
                    />
                  </div>
                  <Button className="w-full" disabled={isLoading}>
                    {isLoading ? "Resetting..." : "Reset Password"}
                  </Button>
                </CardContent>
              </form>
            </Card>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="container relative flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 min-h-[calc(100vh-4rem)] mx-auto">
      <div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
        <div className="absolute inset-0 bg-primary" />
        <div className="relative z-20 flex items-center text-lg font-medium">
          <HeartPulse className="mr-2 h-6 w-6" />
          OncoConnect
        </div>
        <div className="relative z-20 mt-auto">
          <blockquote className="space-y-2">
            <p className="text-lg">
              &ldquo;The community here provided me with the strength and information I needed when I felt most alone
              after my diagnosis.&rdquo;
            </p>
            <footer className="text-sm">Sofia M., Community Member</footer>
          </blockquote>
        </div>
      </div>
      <div className="p-4 lg:p-8">
        <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
          <Card className="border-none shadow-none sm:shadow-sm sm:border">
            <CardHeader className="space-y-1">
              <CardTitle className="text-2xl text-center">Welcome back</CardTitle>
              <CardDescription className="text-center">Enter your email to sign in to your account</CardDescription>
            </CardHeader>
            <form onSubmit={form.handleSubmit(onSubmit)}>
              <CardContent className="grid gap-4">
                {error && (
                  <div className="p-3 text-sm font-medium text-destructive bg-destructive/10 rounded-md text-center flex flex-col gap-2">
                    {error}
                    {unverifiedEmail && (
                      <button
                        type="button"
                        onClick={handleResend}
                        disabled={isLoading}
                        className="text-xs underline underline-offset-2 hover:text-destructive/80"
                      >
                        Resend verification code
                      </button>
                    )}
                  </div>
                )}
                {resendStatus && (
                  <div className="p-3 text-sm font-medium text-green-600 bg-green-100 rounded-md text-center">
                    {resendStatus}
                  </div>
                )}
                {success && (
                  <div className="p-3 text-sm font-medium text-green-600 bg-green-100 rounded-md text-center">
                    {success}
                  </div>
                )}
                <div className="grid gap-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="m@example.com"
                    {...form.register("email")}
                  />
                  {form.formState.errors.email && (
                    <p className="text-xs text-destructive">{form.formState.errors.email.message}</p>
                  )}
                </div>
                <div className="grid gap-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="password">Password</Label>
                    <button
                      type="button"
                      onClick={() => setIsForgotMode(true)}
                      className="text-xs text-muted-foreground hover:text-primary underline underline-offset-4"
                    >
                      Forgot password?
                    </button>
                  </div>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      {...form.register("password")}
                      className="pr-10"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                  {form.formState.errors.password && (
                    <p className="text-xs text-destructive">{form.formState.errors.password.message}</p>
                  )}
                </div>
                <Button className="w-full" disabled={isLoading}>
                  {isLoading ? "Signing In..." : "Sign In"}
                </Button>
              </CardContent>
            </form>
            <CardFooter className="flex flex-col gap-4">
              <div className="text-sm text-center text-muted-foreground">
                Don&apos;t have an account?{" "}
                <Link href="/register" className="underline underline-offset-4 hover:text-primary">
                  Sign up
                </Link>
              </div>
            </CardFooter>
          </Card>
        </div>
      </div>
    </div>
  )
}
