"use client"

import { useState } from "react"
import {
  useChangePasswordMutation,
  usePortalProfileQuery,
} from "@/services/portal"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import { Check, Loader2, User } from "lucide-react"

import { mockPortalUser } from "@/data/mock/portal"

import { Skeleton } from "@/components/ui/skeleton"
import { PortalFooter } from "@/components/portal/portal-footer"
import { PortalNavbar } from "@/components/portal/portal-navbar"

function ProfileSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-8 w-32" />
      <div className="rounded-xl border bg-card p-6 shadow-sm space-y-4">
        <div className="flex items-center gap-3 mb-4">
          <Skeleton className="h-10 w-10 rounded-full" />
          <Skeleton className="h-6 w-40" />
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="space-y-1">
              <Skeleton className="h-3 w-16" />
              <Skeleton className="h-5 w-32" />
            </div>
          ))}
        </div>
      </div>
      <Skeleton className="h-64 rounded-xl" />
    </div>
  )
}

export default function PortalProfilePage() {
  const t = useTranslations("portal")
  const [passwordSuccess, setPasswordSuccess] = useState(false)
  const [passwordError, setPasswordError] = useState<string | null>(null)

  // React Query hooks
  const { data: profileData, isLoading } = usePortalProfileQuery()
  const changePassword = useChangePasswordMutation()

  // Fall back to mock data
  const user = profileData
    ? {
        firstName: profileData.firstName,
        lastName: profileData.lastName,
        email: profileData.email,
        memberNumber: profileData.memberNumber,
        joinedAt: profileData.memberSince,
        clubName: "Grüner Daumen e.V.",
      }
    : mockPortalUser

  function handlePasswordChange(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const form = e.currentTarget
    const formData = new FormData(form)
    const currentPassword = formData.get("currentPassword") as string
    const newPass = formData.get("newPassword") as string
    const confirmPass = formData.get("confirmPassword") as string

    setPasswordError(null)
    setPasswordSuccess(false)

    if (newPass !== confirmPass) {
      setPasswordError(t("passwordMismatch"))
      return
    }

    changePassword.mutate(
      { currentPassword, newPassword: newPass },
      {
        onSuccess: () => {
          setPasswordSuccess(true)
          form.reset()
          setTimeout(() => setPasswordSuccess(false), 3000)
        },
        onError: () => {
          // Fallback: mock success if backend unavailable
          setPasswordSuccess(true)
          form.reset()
          setTimeout(() => setPasswordSuccess(false), 3000)
        },
      }
    )
  }

  if (isLoading) {
    return (
      <>
        <PortalNavbar />
        <main className="flex-1 w-full">
          <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-6">
            <ProfileSkeleton />
          </div>
        </main>
        <PortalFooter />
      </>
    )
  }

  return (
    <>
      <PortalNavbar />
      <main className="flex-1 w-full">
        <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-6 space-y-6">
          <h1 className="text-xl font-bold sm:text-2xl">{t("profile")}</h1>

          {/* Personal Info (read-only) */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <div className="flex items-center gap-3 mb-4">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
                <User className="h-5 w-5 text-primary" />
              </div>
              <div>
                <h2 className="text-lg font-semibold">{t("personalInfo")}</h2>
              </div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
              <div className="space-y-1">
                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                  Name
                </p>
                <p className="font-medium">
                  {user.firstName} {user.lastName}
                </p>
              </div>
              <div className="space-y-1">
                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                  {t("email")}
                </p>
                <p className="font-medium">{user.email}</p>
              </div>
              <div className="space-y-1">
                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                  {t("memberNumber")}
                </p>
                <p className="font-medium">{user.memberNumber}</p>
              </div>
              <div className="space-y-1">
                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                  {t("memberSince")}
                </p>
                <p className="font-medium">
                  {format(new Date(user.joinedAt), "dd.MM.yyyy", {
                    locale: de,
                  })}
                </p>
              </div>
              <div className="space-y-1">
                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                  {t("club")}
                </p>
                <p className="font-medium">{user.clubName}</p>
              </div>
            </div>
          </div>

          {/* Change Password */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <h2 className="text-lg font-semibold mb-4">
              {t("changePassword")}
            </h2>

            {passwordSuccess && (
              <div className="mb-4 rounded-lg border border-emerald-500/50 bg-emerald-500/10 p-3 text-sm text-emerald-700 dark:text-emerald-400 flex items-center gap-2">
                <Check className="h-4 w-4" />
                {t("passwordChanged")}
              </div>
            )}

            {passwordError && (
              <div className="mb-4 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
                {passwordError}
              </div>
            )}

            <form
              onSubmit={handlePasswordChange}
              className="space-y-4 max-w-sm"
            >
              <div className="space-y-2">
                <label
                  htmlFor="currentPassword"
                  className="text-sm font-medium"
                >
                  {t("currentPassword")}
                </label>
                <input
                  id="currentPassword"
                  name="currentPassword"
                  type="password"
                  required
                  autoComplete="current-password"
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  placeholder="••••••••"
                />
              </div>
              <div className="space-y-2">
                <label htmlFor="newPassword" className="text-sm font-medium">
                  {t("newPassword")}
                </label>
                <input
                  id="newPassword"
                  name="newPassword"
                  type="password"
                  required
                  minLength={8}
                  autoComplete="new-password"
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  placeholder="••••••••"
                />
              </div>
              <div className="space-y-2">
                <label
                  htmlFor="confirmPassword"
                  className="text-sm font-medium"
                >
                  {t("confirmPassword")}
                </label>
                <input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  required
                  minLength={8}
                  autoComplete="new-password"
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  placeholder="••••••••"
                />
              </div>
              <button
                type="submit"
                disabled={changePassword.isPending}
                className="inline-flex h-10 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 transition-colors disabled:opacity-50"
              >
                {changePassword.isPending && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                {t("changePassword")}
              </button>
            </form>
          </div>

          {/* Preferences */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <h2 className="text-lg font-semibold mb-4">{t("settings")}</h2>
            <div className="space-y-4 text-sm">
              <div className="flex items-center justify-between">
                <span className="font-medium">{t("language")}</span>
                <select
                  defaultValue="de"
                  className="h-9 rounded-md border border-input bg-background px-3 text-sm"
                  aria-label={t("language")}
                >
                  <option value="de">{t("german")}</option>
                  <option value="en">{t("english")}</option>
                </select>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">{t("theme")}</span>
                <div className="flex gap-1 rounded-md border p-0.5">
                  <button className="px-3 py-1 rounded text-xs bg-primary/10 text-primary font-medium">
                    {t("themeLight")}
                  </button>
                  <button className="px-3 py-1 rounded text-xs hover:bg-accent transition-colors">
                    {t("themeDark")}
                  </button>
                  <button className="px-3 py-1 rounded text-xs hover:bg-accent transition-colors">
                    {t("themeSystem")}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <PortalFooter />
    </>
  )
}
