"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import { Eye, EyeOff, Mail, Lock, Facebook, ArrowRight } from "lucide-react"
import { login } from "@/services/users/query"
import Header from "@/components/features/header/header"
import { useTranslation } from "react-i18next"
import { useLanguage } from "@/contexts/language-context"

export default function LoginPage() {
  const { t } = useTranslation()
  const { isReady } = useLanguage()
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")

  const domain = process.env.NEXT_PUBLIC_API_BASE_URL?.replace("/api", "") || ""

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError("")

    try {
      // Use the login service function
      const result = await login(email, password)

      if (!result.success) {
        setError(result.message || t("login.loginFailed"))
        setIsLoading(false)
        return
      }

      console.log("Login successful, redirecting...")

      // Redirect based on role
      const userRoles = result.data.roles
      if (userRoles.includes("admin")) {
        router.push("/admin")
      } else if (userRoles.includes("student")) {
        router.push("/student")
      } else {
        router.push("/")
      }
    } catch (err: any) {
      setError(err.message || t("login.unexpectedError"))
      setIsLoading(false)
    }
  }

  const handleDevLogin = (role: string) => {
    // For development purposes only
    const loginInfo = {
      token: `dev-${role}-token`,
      name: `Dev ${role.charAt(0).toUpperCase() + role.slice(1)}`,
      email: `dev-${role}@worldmind.com`,
      user_id: `dev-${role}-123`,
      roles: [role], // Now using roles as an array
      logged_in_status: true,
      loggedin_at: new Date().toISOString(),
    }

    localStorage.setItem("login_info", JSON.stringify(loginInfo))

    // Redirect based on role
    if (role === "admin") {
      router.push("/admin")
    } else if (role === "instructor") {
      router.push("/instructor")
    } else {
      router.push("/student")
    }
  }

  // Show loading state while translations are loading
  if (!isReady) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-gray-600">Loading...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Use the shared Header component */}
      <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 - Welcome 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">{t("login.welcomeBack")}</h1>
              <p className="text-lg text-gray-600">{t("login.welcomeDescription")}</p>
            </div>

            <div className="space-y-6">
              {/* Feature Cards */}
              <Card className="border-0 bg-primary-light overflow-hidden rounded-lg">
                <CardContent className="p-6 flex items-start space-x-4">
                  <div className="h-12 w-12 rounded-full bg-primary flex items-center justify-center shrink-0">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="h-6 w-6 text-secondary"
                    >
                      <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
                      <path d="M13.73 21a2 2 0 0 1-3.46 0" />
                    </svg>
                  </div>
                  <div>
                    <h3 className="font-bold text-secondary">{t("login.personalizedLearning")}</h3>
                    <p className="text-sm text-gray-700">{t("login.personalizedLearningDesc")}</p>
                  </div>
                </CardContent>
              </Card>

              <Card className="border-0 bg-secondary-light overflow-hidden rounded-lg">
                <CardContent className="p-6 flex items-start space-x-4">
                  <div className="h-12 w-12 rounded-full bg-secondary flex items-center justify-center shrink-0">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="h-6 w-6 text-primary"
                    >
                      <circle cx="12" cy="12" r="10" />
                      <path d="M12 6v6l4 2" />
                    </svg>
                  </div>
                  <div>
                    <h3 className="font-bold text-secondary">{t("login.scheduledSessions")}</h3>
                    <p className="text-sm text-gray-700">{t("login.scheduledSessionsDesc")}</p>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>

          {/* Right Column - Login Form */}
          <div>
            <Card className="border-0 shadow-lg overflow-hidden rounded-lg">
              <CardHeader className="bg-gradient-to-r from-secondary to-secondary-dark text-white p-6 rounded-t-lg">
                <CardTitle className="text-2xl font-bold text-white">{t("login.signIn")}</CardTitle>
                <CardDescription className="text-white/80">{t("login.signInDescription")}</CardDescription>
              </CardHeader>

              <Tabs defaultValue="email" className="w-full">
                <div className="px-6 pt-6">
                  <TabsList className="grid w-full grid-cols-2 mb-4 rounded-md">
                    <TabsTrigger
                      value="email"
                      className="data-[state=active]:bg-primary data-[state=active]:text-secondary rounded-l-md"
                    >
                      {t("login.email")}
                    </TabsTrigger>
                    <TabsTrigger
                      value="social"
                      className="data-[state=active]:bg-primary data-[state=active]:text-secondary rounded-r-md"
                    >
                      {t("login.socialLogin")}
                    </TabsTrigger>
                  </TabsList>
                </div>

                <CardContent className="p-6 pt-2">
                  <TabsContent value="email">
                    <form onSubmit={handleLogin} className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="email" className="text-gray-700">
                          {t("login.email")}
                        </Label>
                        <div className="relative">
                          <Mail className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                          <Input
                            id="email"
                            type="email"
                            placeholder={t("login.emailPlaceholder")}
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            className="pl-10 border-gray-300 focus:border-secondary focus:ring-secondary rounded-md"
                            required
                          />
                        </div>
                      </div>

                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label htmlFor="password" className="text-gray-700">
                            {t("login.password")}
                          </Label>
                          <Link
                            href="/auth/reset-password"
                            className="text-xs text-secondary hover:text-secondary-dark"
                          >
                            {t("login.forgotPassword")}
                          </Link>
                        </div>
                        <div className="relative">
                          <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                          <Input
                            id="password"
                            type={showPassword ? "text" : "password"}
                            placeholder={t("login.passwordPlaceholder")}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="pl-10 border-gray-300 focus:border-secondary focus:ring-secondary rounded-md"
                            required
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-3 top-3 text-gray-400 hover:text-gray-600"
                          >
                            {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                          </button>
                        </div>
                      </div>

                      {error && <div className="bg-red-50 text-red-500 p-3 rounded-md text-sm">{error}</div>}

                      <Button
                        type="submit"
                        className="w-full bg-primary hover:bg-primary-medium text-secondary font-medium rounded-md"
                        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>
                            {t("login.signingIn")}
                          </span>
                        ) : (
                          <span className="flex items-center justify-center">
                            {t("login.signInButton")} <ArrowRight className="ml-2 h-4 w-4" />
                          </span>
                        )}
                      </Button>

                      <Link href="/auth/first-time" className="w-full">
                        <Button
                          type="button"
                          variant="outline"
                          className="w-full border-gray-300 hover:bg-gray-50 text-gray-700 font-medium rounded-md mt-3"
                        >
                          First Time Login
                        </Button>
                      </Link>
                    </form>
                  </TabsContent>

                  <TabsContent value="social">
                    <div className="space-y-4">
                      <Button
                        variant="outline"
                        className="w-full border-gray-300 hover:bg-red-50 hover:text-red-600 hover:border-red-400 rounded-md"
                        onClick={() => (window.location.href = `${domain}/auth/socmed/google/redirect`)}
                      >
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 24 24"
                          className="mr-2 h-4 w-4"
                          fill="currentColor"
                        >
                          <path d="M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z" />
                        </svg>
                        {t("login.continueWithGoogle")}
                      </Button>
                      <Button
                        variant="outline"
                        className="w-full border-gray-300 hover:bg-blue-50 hover:text-blue-600 hover:border-blue-400 rounded-md"
                        onClick={() => (window.location.href = `${domain}/auth/socmed/facebook/redirect`)}
                      >
                        <Facebook className="mr-2 h-4 w-4" />
                        {t("login.continueWithFacebook")}
                      </Button>
                    </div>
                  </TabsContent>
                </CardContent>
              </Tabs>

              <Separator />

              {process.env.NODE_ENV === "development" && (
                <CardFooter className="p-6 bg-gray-50 rounded-b-lg">
                  <div className="w-full">
                    <p className="text-xs text-gray-500 font-medium mb-3">{t("login.devLogins")}</p>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        className="text-xs h-8 bg-white hover:bg-secondary-light hover:text-secondary border-gray-200 rounded-md"
                        onClick={() => handleDevLogin("student")}
                      >
                        {t("login.student")}
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        className="text-xs h-8 bg-white hover:bg-gray-100 hover:text-gray-800 border-gray-200 rounded-md"
                        onClick={() => handleDevLogin("admin")}
                      >
                        {t("login.admin")}
                      </Button>
                    </div>
                  </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">
          {t("login.copyright", { year: new Date().getFullYear() })}
        </div>
      </footer>
    </div>
  )
}
