"use client"

import { FormEvent, useMemo, useState } from "react"
import Link from "next/link"
import { toast } from "sonner"
import { Bell } from "lucide-react"

import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"

interface PortalProfileSettingsProps {
  initialEmail: string
}

export function PortalProfileSettings({ initialEmail }: PortalProfileSettingsProps) {
  const [email, setEmail] = useState(initialEmail)
  const [referenceEmail, setReferenceEmail] = useState(initialEmail)
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const hasChanges = useMemo(() => {
    const normalizedEmail = email.trim().toLowerCase()
    const emailChanged = normalizedEmail !== referenceEmail.trim().toLowerCase()
    const passwordChanged = newPassword.length > 0 || confirmPassword.length > 0
    return emailChanged || passwordChanged
  }, [email, referenceEmail, newPassword, confirmPassword])

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!hasChanges) {
      toast.info("Nenhuma alteração a salvar.")
      return
    }

    const payload: Record<string, unknown> = {}
    const trimmedEmail = email.trim()
    if (trimmedEmail && trimmedEmail.toLowerCase() !== referenceEmail.trim().toLowerCase()) {
      payload.email = trimmedEmail
    }
    if (newPassword || confirmPassword) {
      payload.password = { newPassword, confirmPassword }
    }

    setIsSubmitting(true)
    try {
      const res = await fetch("/api/portal/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({ error: "Falha ao atualizar perfil" }))
        const message = typeof data.error === "string" ? data.error : "Falha ao atualizar perfil"
        toast.error(message)
        return
      }
      const data = (await res.json().catch(() => null)) as { email?: string } | null
      if (data?.email) {
        setEmail(data.email)
        setReferenceEmail(data.email)
      }
      setNewPassword("")
      setConfirmPassword("")
      toast.success("Dados atualizados com sucesso!")
    } catch (error) {
      console.error("Falha ao atualizar perfil", error)
      toast.error("Não foi possível atualizar o perfil agora.")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
      <CardHeader>
        <CardTitle className="text-lg font-semibold text-neutral-900">Meu perfil</CardTitle>
        <CardDescription className="text-sm text-neutral-600">
          Ajuste seu e-mail de acesso e defina uma senha para entrar pelo navegador.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-2">
            <label className="text-sm font-medium text-neutral-800" htmlFor="profile-email">
              E-mail
            </label>
            <Input
              id="profile-email"
              type="email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              placeholder="seuemail@empresa.com"
            />
          </div>
          <div className="grid gap-2">
            <label className="text-sm font-medium text-neutral-800" htmlFor="profile-password">
              Nova senha
            </label>
            <Input
              id="profile-password"
              type="password"
              value={newPassword}
              onChange={(event) => setNewPassword(event.target.value)}
              placeholder="Digite a nova senha"
            />
            <Input
              type="password"
              value={confirmPassword}
              onChange={(event) => setConfirmPassword(event.target.value)}
              placeholder="Confirme a nova senha"
            />
            <p className="text-xs text-neutral-500">
              Utilize pelo menos 8 caracteres. Deixe os campos em branco caso não queira alterar a senha.
            </p>
          </div>
          <div className="flex justify-end">
            <Button type="submit" disabled={isSubmitting || !hasChanges}>
              {isSubmitting ? "Salvando..." : "Salvar alteracoes"}
            </Button>
          </div>
        </form>
      </CardContent>
      <CardFooter className="border-t bg-muted/30 px-6 py-4">
        <div className="flex items-center justify-between w-full">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Bell className="h-4 w-4" />
            <span>Configurar notificacoes por e-mail</span>
          </div>
          <Button variant="outline" size="sm" asChild>
            <Link href="/portal/profile/notifications">
              Preferencias
            </Link>
          </Button>
        </div>
      </CardFooter>
    </Card>
  )
}
