"use client"

import { useEffect, useState } from "react"
import { ChevronDown, ChevronUp, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useMailAccount } from "@/lib/api/hooks/use-mail-account"
import { useUpdateMailAccount } from "@/lib/api/hooks/use-mail-account-mutations"
import { useTestMailAccount } from "@/lib/api/hooks/use-mail-account-test"
import type { ApiMailAccount, ApiMailAccountDetail, UpdateMailAccountPayload } from "@/lib/api/types"

function parsePort(value: string, fallback: number): number {
  const n = Number.parseInt(value, 10)
  return Number.isFinite(n) && n > 0 ? n : fallback
}

function asString(value: string | undefined | null): string {
  return value ?? ""
}

function trimField(value: string | undefined | null): string {
  return asString(value).trim()
}

type EditAccountFormState = {
  name: string
  email: string
  username: string
  password: string
  imap_host: string
  imap_port: string
  imap_tls: boolean
  smtp_host: string
  smtp_port: string
  smtp_tls: boolean
}

function formStateFromAccount(
  account: ApiMailAccount,
  detail?: ApiMailAccountDetail | null
): EditAccountFormState {
  const src = detail ?? account
  return {
    name: asString(src.name ?? account.name),
    email: asString(src.email ?? account.email),
    username: asString(detail?.username ?? detail?.email ?? account.email),
    password: "",
    imap_host: asString(detail?.imap_host ?? account.imap_host),
    imap_port: String(detail?.imap_port ?? 993),
    imap_tls: detail?.imap_tls ?? true,
    smtp_host: asString(detail?.smtp_host ?? account.smtp_host),
    smtp_port: String(detail?.smtp_port ?? 587),
    smtp_tls: detail?.smtp_tls ?? true,
  }
}

export function EditMailAccountForm({
  account,
  onCancel,
}: {
  account: ApiMailAccount
  onCancel: () => void
}) {
  const { data: detail, isPending, isError, refetch } = useMailAccount(account.id)
  const updateAccount = useUpdateMailAccount(account.id)
  const testMutation = useTestMailAccount(account.id)
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [testOk, setTestOk] = useState<boolean | null>(null)
  const [form, setForm] = useState<EditAccountFormState>(() => formStateFromAccount(account))

  const isOAuth = detail?.auth_type === "oauth2"

  useEffect(() => {
    if (!detail) return
    setForm(formStateFromAccount(account, detail))
    setTestOk(null)
  }, [account, detail])

  if (isPending && !detail) {
    return null
  }

  if (isError) {
    return (
      <div className="space-y-2">
        <p className="text-sm text-destructive">Impossible de charger ce compte.</p>
        <Button type="button" size="sm" variant="outline" onClick={() => void refetch()}>
          Réessayer
        </Button>
      </div>
    )
  }

  function buildPayload(): UpdateMailAccountPayload {
    return {
      name: trimField(form.name) || trimField(form.email),
      email: trimField(form.email),
      provider: detail?.provider,
      imap_host: trimField(form.imap_host),
      imap_port: parsePort(form.imap_port, 993),
      imap_tls: form.imap_tls,
      smtp_host: trimField(form.smtp_host),
      smtp_port: parsePort(form.smtp_port, 587),
      smtp_tls: form.smtp_tls,
      username: trimField(form.username),
      password: form.password || undefined,
    }
  }

  async function runConnectionTest() {
    setTestOk(null)
    try {
      const result = await testMutation.mutateAsync({
        imap_host: trimField(form.imap_host),
        imap_port: parsePort(form.imap_port, 993),
        imap_tls: form.imap_tls,
        smtp_host: trimField(form.smtp_host),
        smtp_port: parsePort(form.smtp_port, 587),
        smtp_tls: form.smtp_tls,
        username: trimField(form.username) || undefined,
        password: form.password || undefined,
        ...(isOAuth ? { auth_type: "oauth2" as const } : {}),
      })
      setTestOk(result.ok)
    } catch {
      setTestOk(false)
    }
  }

  const canTestConnection =
    Boolean(trimField(form.imap_host)) && Boolean(trimField(form.smtp_host))

  function handleSave() {
    const payload = buildPayload()
    if (!isOAuth && form.password && testOk === false) return
    updateAccount.mutate(payload, { onSuccess: onCancel })
  }

  const passwordChanged = Boolean(form.password)
  const canSave =
    !updateAccount.isPending &&
    Boolean(trimField(form.email)) &&
    Boolean(trimField(form.imap_host)) &&
    Boolean(trimField(form.smtp_host)) &&
    (isOAuth || Boolean(trimField(form.username))) &&
    (!passwordChanged || testOk !== false)

  return (
    <div className="space-y-4 rounded-lg border border-border bg-muted/20 p-4">
      <h3 className="text-sm font-medium">Modifier la connexion</h3>

      {isOAuth ? (
        <p className="text-xs text-muted-foreground">
          Compte connecté via OAuth
          {detail?.oauth_provider ? ` (${detail.oauth_provider})` : ""}. Vous pouvez ajuster le
          nom et les serveurs ; le mot de passe n&apos;est pas utilisé.
        </p>
      ) : null}

      <div className="grid gap-3 sm:grid-cols-2 max-w-2xl">
        <Field
          label="Nom affiché"
          value={form.name}
          onChange={(v) => setForm({ ...form, name: v })}
        />
        <Field
          label="Adresse e-mail"
          type="email"
          value={form.email}
          onChange={(v) => setForm({ ...form, email: v })}
        />
        <Field
          label="Identifiant"
          value={form.username}
          onChange={(v) => setForm({ ...form, username: v })}
          autoComplete="username"
        />
        {!isOAuth ? (
          <Field
            label="Nouveau mot de passe"
            type="password"
            value={form.password}
            placeholder="Laisser vide pour ne pas changer"
            onChange={(v) => {
              setTestOk(null)
              setForm({ ...form, password: v })
            }}
            autoComplete="new-password"
          />
        ) : null}
      </div>

      <div>
        <button
          type="button"
          className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
          onClick={() => setShowAdvanced((v) => !v)}
        >
          {showAdvanced ? <ChevronUp className="size-4" /> : <ChevronDown className="size-4" />}
          Paramètres serveur {showAdvanced ? "" : "(avancé)"}
        </button>
        {showAdvanced ? (
          <div className="mt-3 grid gap-3 sm:grid-cols-2 max-w-2xl">
            <Field
              label="IMAP hôte"
              value={form.imap_host}
              onChange={(v) => setForm({ ...form, imap_host: v })}
            />
            <Field
              label="IMAP port"
              value={form.imap_port}
              onChange={(v) => setForm({ ...form, imap_port: v })}
            />
            <Field
              label="SMTP hôte"
              value={form.smtp_host}
              onChange={(v) => setForm({ ...form, smtp_host: v })}
            />
            <Field
              label="SMTP port"
              value={form.smtp_port}
              onChange={(v) => setForm({ ...form, smtp_port: v })}
            />
            <label className="flex items-center gap-2 text-sm sm:col-span-2">
              <input
                type="checkbox"
                checked={form.imap_tls}
                onChange={(e) => setForm({ ...form, imap_tls: e.target.checked })}
              />
              IMAP TLS
            </label>
            <label className="flex items-center gap-2 text-sm sm:col-span-2">
              <input
                type="checkbox"
                checked={form.smtp_tls}
                onChange={(e) => setForm({ ...form, smtp_tls: e.target.checked })}
              />
              SMTP TLS / STARTTLS
            </label>
          </div>
        ) : (
          <p className="mt-1 text-xs text-muted-foreground">
            Réception {form.imap_host}:{form.imap_port} · Envoi {form.smtp_host}:{form.smtp_port}
          </p>
        )}
      </div>

      <div className="space-y-2">
        {testOk === true ? (
          <p className="text-sm text-green-600 dark:text-green-500">
            Connexion IMAP et SMTP validée.
          </p>
        ) : null}
        {testOk === false ? (
          <div className="text-sm text-destructive space-y-1">
            <p>Échec du test de connexion.</p>
            {testMutation.data?.imap_error ? (
              <p className="text-xs">IMAP : {testMutation.data.imap_error}</p>
            ) : null}
            {testMutation.data?.smtp_error ? (
              <p className="text-xs">SMTP : {testMutation.data.smtp_error}</p>
            ) : null}
          </div>
        ) : null}
        <Button
          type="button"
          variant="outline"
          size="sm"
          disabled={testMutation.isPending || !canTestConnection}
          onClick={() => void runConnectionTest()}
        >
          {testMutation.isPending ? (
            <>
              <Loader2 className="mr-2 size-4 animate-spin" />
              Test…
            </>
          ) : (
            "Tester la connexion"
          )}
        </Button>
        {!isOAuth && !passwordChanged ? (
          <p className="text-xs text-muted-foreground">
            Le mot de passe enregistré est utilisé si le champ ci-dessus est vide.
          </p>
        ) : null}
      </div>

      <div className="flex flex-wrap gap-2">
        <Button type="button" size="sm" disabled={!canSave} onClick={handleSave}>
          {updateAccount.isPending ? (
            <>
              <Loader2 className="mr-2 size-4 animate-spin" />
              Enregistrement…
            </>
          ) : (
            "Enregistrer"
          )}
        </Button>
        <Button type="button" size="sm" variant="ghost" onClick={onCancel}>
          Annuler
        </Button>
      </div>
    </div>
  )
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  autoComplete,
  placeholder,
}: {
  label: string
  value: string
  onChange: (value: string) => void
  type?: string
  autoComplete?: string
  placeholder?: string
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs">{label}</Label>
      <Input
        value={value}
        type={type}
        autoComplete={autoComplete}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  )
}
