"use client"

import { useEffect, useMemo, useState, type ChangeEvent } from "react"
import { useRouter } from "next/navigation"
import { ArrowLeft } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useTaskStore } from "@/stores/useTaskStore"
import { buildAvatarPresets, generateAvatarDataUrl, getInitials } from "@/lib/avatar"

const readImageFileAsDataUrl = (file: File) =>
  new Promise<string>((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(String(reader.result || ""))
    reader.onerror = () => reject(new Error("Failed to read image"))
    reader.readAsDataURL(file)
  })

export default function SettingsPage() {
  const router = useRouter()
  const { setCurrentUser } = useTaskStore()

  const [authReady, setAuthReady] = useState(false)
  const [isSavingProfile, setIsSavingProfile] = useState(false)
  const [isSavingPassword, setIsSavingPassword] = useState(false)
  const [isLoggingOut, setIsLoggingOut] = useState(false)
  const [profileError, setProfileError] = useState<string | null>(null)
  const [profileSuccess, setProfileSuccess] = useState<string | null>(null)
  const [passwordError, setPasswordError] = useState<string | null>(null)
  const [passwordSuccess, setPasswordSuccess] = useState<string | null>(null)

  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [profileAvatarUrl, setProfileAvatarUrl] = useState("")
  const [currentUserId, setCurrentUserId] = useState("")
  const [initialEmail, setInitialEmail] = useState("")
  const [profileCurrentPassword, setProfileCurrentPassword] = useState("")
  const [currentPassword, setCurrentPassword] = useState("")
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")

  useEffect(() => {
    let isMounted = true
    const loadSession = async () => {
      try {
        const res = await fetch("/api/auth/session", { cache: "no-store" })
        if (!res.ok) {
          if (isMounted) router.replace("/login")
          return
        }
        const data = await res.json().catch(() => null)
        const user = data?.user
        if (
          !user
          || typeof user.id !== "string"
          || typeof user.name !== "string"
          || typeof user.email !== "string"
        ) {
          if (isMounted) router.replace("/login")
          return
        }
        if (!isMounted) return

        setName(user.name || "")
        setEmail(user.email || "")
        setProfileAvatarUrl(typeof user.avatarUrl === "string" ? user.avatarUrl : "")
        setCurrentUserId(user.id || "")
        setInitialEmail(user.email || "")
        setCurrentUser({
          id: user.id,
          name: user.name,
          email: user.email,
          avatarUrl: typeof user.avatarUrl === "string" ? user.avatarUrl : undefined,
        })
        setAuthReady(true)
      } catch {
        if (isMounted) router.replace("/login")
      }
    }

    loadSession()
    return () => {
      isMounted = false
    }
  }, [router, setCurrentUser])

  const handleProfileSave = async () => {
    setProfileError(null)
    setProfileSuccess(null)

    const trimmedName = name.trim()
    const trimmedEmail = email.trim()

    if (!trimmedName || !trimmedEmail) {
      setProfileError("Name and email are required")
      return
    }

    const emailChanged = trimmedEmail.toLowerCase() !== initialEmail.toLowerCase()
    if (emailChanged && !profileCurrentPassword) {
      setProfileError("Current password is required to change email")
      return
    }

    setIsSavingProfile(true)
    try {
      const payload: {
        name: string
        email: string
        avatarUrl: string | null
        currentPassword?: string
      } = {
        name: trimmedName,
        email: trimmedEmail,
        avatarUrl: profileAvatarUrl || null,
      }
      if (emailChanged) payload.currentPassword = profileCurrentPassword

      const res = await fetch("/api/auth/account", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })

      const data = await res.json().catch(() => null)
      if (!res.ok) {
        setProfileError(
          data && typeof data.error === "string" ? data.error : "Failed to update profile"
        )
        return
      }
      const user = data?.user
      if (
        !user
        || typeof user.id !== "string"
        || typeof user.name !== "string"
        || typeof user.email !== "string"
      ) {
        setProfileError("Profile update returned invalid data")
        return
      }

      setCurrentUser({
        id: user.id,
        name: user.name,
        email: user.email,
        avatarUrl: typeof user.avatarUrl === "string" ? user.avatarUrl : undefined,
      })
      setName(user.name)
      setEmail(user.email)
      setProfileAvatarUrl(typeof user.avatarUrl === "string" ? user.avatarUrl : "")
      setCurrentUserId(user.id)
      setInitialEmail(user.email)
      setProfileCurrentPassword("")
      setProfileSuccess("Profile updated")
    } catch {
      setProfileError("Failed to update profile")
    } finally {
      setIsSavingProfile(false)
    }
  }

  const handleAvatarUpload = async (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    event.target.value = ""
    if (!file) return
    if (!file.type.startsWith("image/")) {
      setProfileError("Please choose an image file")
      return
    }
    try {
      const dataUrl = await readImageFileAsDataUrl(file)
      setProfileAvatarUrl(dataUrl)
      setProfileError(null)
      setProfileSuccess(null)
    } catch {
      setProfileError("Failed to load image")
    }
  }

  const avatarSeed = currentUserId || email || name || "user"
  const generatedAvatarUrl = useMemo(
    () => generateAvatarDataUrl(avatarSeed, name || email || "User"),
    [avatarSeed, name, email]
  )
  const avatarPresets = useMemo(
    () =>
      Array.from(new Set(buildAvatarPresets(avatarSeed, name || email || "User", 8))).map((url, index) => ({
        id: index,
        url,
      })),
    [avatarSeed, name, email]
  )
  const profilePreviewAvatarUrl = profileAvatarUrl || generatedAvatarUrl

  const handlePasswordSave = async () => {
    setPasswordError(null)
    setPasswordSuccess(null)

    if (!currentPassword) {
      setPasswordError("Current password is required")
      return
    }
    if (!newPassword) {
      setPasswordError("New password is required")
      return
    }
    if (newPassword !== confirmPassword) {
      setPasswordError("New password and confirmation do not match")
      return
    }

    setIsSavingPassword(true)
    try {
      const res = await fetch("/api/auth/account", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          currentPassword,
          newPassword,
        }),
      })

      const data = await res.json().catch(() => null)
      if (!res.ok) {
        setPasswordError(
          data && typeof data.error === "string" ? data.error : "Failed to update password"
        )
        return
      }

      setCurrentPassword("")
      setNewPassword("")
      setConfirmPassword("")
      setPasswordSuccess("Password updated")
    } catch {
      setPasswordError("Failed to update password")
    } finally {
      setIsSavingPassword(false)
    }
  }

  const handleLogout = async () => {
    setIsLoggingOut(true)
    try {
      await fetch("/api/auth/logout", { method: "POST" })
      router.replace("/login")
    } finally {
      setIsLoggingOut(false)
    }
  }

  if (!authReady) {
    return (
      <div className="min-h-screen bg-slate-950 text-slate-100 flex items-center justify-center">
        <p className="text-sm text-slate-400">Checking session...</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      <div className="max-w-2xl mx-auto p-4 md:p-6 space-y-6">
        <div className="flex items-center justify-between">
          <Button variant="outline" className="border-slate-700 text-slate-200 hover:bg-slate-800" onClick={() => router.push("/")}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Board
          </Button>
          <Button
            variant="outline"
            className="border-slate-700 text-slate-200 hover:bg-slate-800"
            onClick={handleLogout}
            disabled={isLoggingOut}
          >
            {isLoggingOut ? "Logging out..." : "Logout"}
          </Button>
        </div>

        <div className="border border-slate-800 rounded-xl bg-slate-900/60 p-5 space-y-5">
          <div>
            <h1 className="text-xl font-semibold text-white">Account Settings</h1>
            <p className="text-sm text-slate-400 mt-1">Update your profile and password.</p>
          </div>

          <div className="space-y-4">
            <div>
              <label className="block text-sm text-slate-300 mb-2">Profile Photo</label>
              <div className="flex items-center gap-3">
                <img
                  src={profilePreviewAvatarUrl}
                  alt={name || "Profile photo"}
                  className="h-14 w-14 rounded-full border border-slate-700 object-cover bg-slate-800"
                />
                <div className="flex items-center gap-2">
                  <label
                    htmlFor="profile-avatar-upload"
                    className="px-3 py-2 rounded-md border border-slate-700 bg-slate-800 text-sm text-slate-200 hover:border-slate-500 cursor-pointer"
                  >
                    Upload
                  </label>
                  <input
                    id="profile-avatar-upload"
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleAvatarUpload}
                  />
                  {profileAvatarUrl && (
                    <Button
                      type="button"
                      variant="ghost"
                      onClick={() => setProfileAvatarUrl("")}
                    >
                      Remove
                    </Button>
                  )}
                </div>
              </div>
              <p className="text-xs text-slate-500 mt-2">
                {profileAvatarUrl ? "Using custom avatar." : `Using generated default avatar (${getInitials(name || email || "User")}).`}
              </p>
              <div className="mt-3">
                <p className="text-xs text-slate-400 mb-2">Or pick a preset:</p>
                <div className="flex flex-wrap gap-2">
                  {avatarPresets.map((preset) => (
                    <button
                      key={preset.id}
                      type="button"
                      onClick={() => setProfileAvatarUrl(preset.url)}
                      className={`rounded-full p-0.5 border ${profileAvatarUrl === preset.url ? "border-blue-400" : "border-slate-700 hover:border-slate-500"}`}
                      title={`Preset ${preset.id + 1}`}
                    >
                      <img
                        src={preset.url}
                        alt={`Preset avatar ${preset.id + 1}`}
                        className="h-8 w-8 rounded-full object-cover"
                      />
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">Name</label>
              <input
                type="text"
                value={name}
                onChange={(event) => setName(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="Your display name"
              />
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">Email</label>
              <input
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="you@example.com"
              />
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">Current Password (only if changing email)</label>
              <input
                type="password"
                value={profileCurrentPassword}
                onChange={(event) => setProfileCurrentPassword(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="Current password"
              />
            </div>
          </div>

          {profileError && <p className="text-sm text-red-400">{profileError}</p>}
          {profileSuccess && <p className="text-sm text-emerald-400">{profileSuccess}</p>}

          <div className="pt-2">
            <Button onClick={handleProfileSave} disabled={isSavingProfile}>
              {isSavingProfile ? "Saving..." : "Save Profile"}
            </Button>
          </div>

          <div className="border-t border-slate-800 pt-4 space-y-4">
            <div>
              <h2 className="text-sm font-medium text-slate-200">Change Password</h2>
              <p className="text-xs text-slate-500 mt-1">Update password separately from profile settings.</p>
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">Current Password</label>
              <input
                type="password"
                value={currentPassword}
                onChange={(event) => setCurrentPassword(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="Current password"
              />
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">New Password</label>
              <input
                type="password"
                value={newPassword}
                onChange={(event) => setNewPassword(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="At least 8 characters"
              />
            </div>

            <div>
              <label className="block text-sm text-slate-300 mb-1">Confirm New Password</label>
              <input
                type="password"
                value={confirmPassword}
                onChange={(event) => setConfirmPassword(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="Confirm new password"
              />
            </div>
          </div>

          {passwordError && <p className="text-sm text-red-400">{passwordError}</p>}
          {passwordSuccess && <p className="text-sm text-emerald-400">{passwordSuccess}</p>}

          <div className="pt-2">
            <Button onClick={handlePasswordSave} disabled={isSavingPassword}>
              {isSavingPassword ? "Saving..." : "Update Password"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
