"use client"

import { useLayoutEffect, useRef } from "react"
import { Icon } from "@iconify/react"
import { ComposeWindow } from "@/components/gmail/compose/compose-window"
import { ProductMailDemoShell } from "@/components/landing/product/product-demos/product-mail-demo-shell"
import {
  type ComposeOpenPreset,
  useComposeActions,
  useComposeWindows,
} from "@/lib/compose-context"

const COMPOSE_PRESET: ComposeOpenPreset = {
  from: {
    name: "Camille Visiteur",
    email: "camille@demo.ulti",
    defaultSignatureId: null,
  },
  to: [{ name: "Alice Martin", email: "alice.martin@yahoo.fr" }],
  subject: "Proposition de rendez-vous — mardi 14h",
  bodyHtml:
    "<p>Bonjour Alice,</p><p>Suite à notre échange, je vous propose un créneau <strong>mardi à 14h</strong> pour finaliser le projet. Dites-moi si cela vous convient.</p><p>— Cordialement,<br>Jean</p>",
  autoInsertSignature: false,
  focusToOnMount: false,
  focusBodyOnMount: false,
  placement: "dock",
}

function ProductComposeDemoInner() {
  const { openComposeWithInitial } = useComposeActions()
  const { composeWindows } = useComposeWindows()
  const seeded = useRef(false)

  useLayoutEffect(() => {
    if (seeded.current) return
    seeded.current = true
    openComposeWithInitial(COMPOSE_PRESET)
  }, [openComposeWithInitial])

  useLayoutEffect(() => {
    if (!seeded.current || composeWindows.length > 0) return
    openComposeWithInitial(COMPOSE_PRESET)
  }, [composeWindows.length, openComposeWithInitial])

  const compose = composeWindows[0]

  if (!compose) {
    return (
      <div className="flex min-h-[34rem] items-center justify-center text-sm text-[var(--landing-muted)] sm:min-h-[36rem]">
        Chargement du compositeur…
      </div>
    )
  }

  return (
    <div className="flex min-h-[34rem] items-end justify-center overflow-visible px-2 pb-6 pt-4 sm:min-h-[36rem] sm:px-4">
      <ComposeWindow compose={compose} />
    </div>
  )
}

export function UltimailComposeDemo() {
  return (
    <div className="flex flex-col gap-3">
      <ProductMailDemoShell>
        <ProductComposeDemoInner />
      </ProductMailDemoShell>
      <p className="flex items-start gap-2 text-sm text-[var(--landing-muted)]">
        <Icon icon="mdi:incognito" className="mt-0.5 size-4 shrink-0" aria-hidden />
        Compositeur réel — mise en forme, PJ et envoi programmé. Rien n&apos;est envoyé.
      </p>
    </div>
  )
}
