"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { OrgSettingsSection } from "@/components/admin/settings/org-settings-form"
import { MigrationProjectsPanel } from "@/components/admin/settings/sections/migration-projects-panel"
import {
  useCreateMailDomain,
  useMailDomains,
  useVerifyMailDomainMX,
  useVerifyMailDomainTXT,
} from "@/lib/api/hooks/use-hosted-mail"

export function MailDomainsSection() {
  const domainsQuery = useMailDomains()
  const createDomain = useCreateMailDomain()
  const [domainName, setDomainName] = useState("")

  const domains = domainsQuery.data?.domains ?? []

  return (
    <div className="space-y-8">
      <OrgSettingsSection
        title="Domaines mail hébergés"
        description="Stalwart — vérification DNS, DKIM et provisioning des boîtes @domaine."
      >
        <div className="grid gap-4 md:grid-cols-[1fr_auto]">
          <div className="space-y-2">
            <Label htmlFor="new-domain">Nouveau domaine</Label>
            <Input
              id="new-domain"
              value={domainName}
              onChange={(e) => setDomainName(e.target.value)}
              placeholder="entreprise.com"
            />
          </div>
          <div className="flex items-end">
            <Button
              disabled={!domainName || createDomain.isPending}
              onClick={() => {
                void createDomain.mutateAsync({ name: domainName }).then(() => setDomainName(""))
              }}
            >
              Ajouter
            </Button>
          </div>
        </div>

        <ul className="mt-6 space-y-3">
          {domains.map((domain) => (
            <DomainRow key={domain.id} domain={domain} />
          ))}
        </ul>
      </OrgSettingsSection>

      <MigrationProjectsPanel domains={domains} />
    </div>
  )
}

function DomainRow({
  domain,
}: {
  domain: {
    id: string
    name: string
    status: string
    verification_token?: string
    is_platform_domain: boolean
  }
}) {
  const verifyTxt = useVerifyMailDomainTXT(domain.id)
  const verifyMx = useVerifyMailDomainMX(domain.id)

  return (
    <li className="rounded-lg border p-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <p className="font-medium">
            {domain.name}
            {domain.is_platform_domain ? " (plateforme)" : ""}
          </p>
          <p className="text-sm text-muted-foreground">Statut : {domain.status}</p>
          {domain.verification_token && (
            <p className="mt-1 text-xs text-muted-foreground">
              TXT : <code>_ultisuite-verify.{domain.name}</code> = {domain.verification_token}
            </p>
          )}
        </div>
        <div className="flex gap-2">
          <Button size="sm" variant="outline" onClick={() => void verifyTxt.mutateAsync()}>
            Vérifier TXT
          </Button>
          <Button size="sm" variant="secondary" onClick={() => void verifyMx.mutateAsync()}>
            Vérifier MX
          </Button>
        </div>
      </div>
    </li>
  )
}
