"use client"

import { useState } from "react"
import { PenLine, Plus, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  useCreateMailSignature,
  useDeleteMailSignature,
  useUpdateMailSignature,
} from "@/lib/api/hooks/use-mail-signatures"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import type { ApiMailSignature } from "@/lib/api/types"

export function SignatureLibraryCard({
  signatures,
  showInitialLoad,
}: {
  signatures: ApiMailSignature[]
  showInitialLoad: boolean
}) {
  const { ready } = useAuthReady()
  const createSignature = useCreateMailSignature()
  const updateSignature = useUpdateMailSignature()
  const deleteSignature = useDeleteMailSignature()
  const [showAddForm, setShowAddForm] = useState(false)
  const [draft, setDraft] = useState({ name: "", html: "" })

  function handleCreate() {
    const name = draft.name.trim()
    if (!name) return
    createSignature.mutate(
      { name, html: draft.html },
      {
        onSuccess: () => {
          setShowAddForm(false)
          setDraft({ name: "", html: "" })
        },
      }
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base flex items-center gap-2">
          <PenLine className="size-4" />
          Signatures
        </CardTitle>
        <CardDescription>
          Créez des signatures nommées réutilisables sur vos identités d&apos;envoi.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {!ready || showInitialLoad ? null : signatures.length === 0 ? (
          <p className="text-sm text-muted-foreground">Aucune signature enregistrée.</p>
        ) : (
          <ul className="space-y-3">
            {signatures.map((signature) => (
              <li
                key={signature.id}
                className="rounded-lg border border-border p-3 space-y-2"
              >
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 space-y-2">
                    <div className="space-y-1">
                      <Label className="text-xs">Nom</Label>
                      <Input
                        defaultValue={signature.name}
                        onBlur={(e) => {
                          const next = e.target.value.trim()
                          if (!next || next === signature.name) return
                          updateSignature.mutate({
                            signatureId: signature.id,
                            name: next,
                            html: signature.html,
                          })
                        }}
                      />
                    </div>
                  </div>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    aria-label="Supprimer la signature"
                    onClick={() => deleteSignature.mutate(signature.id)}
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">Contenu HTML</Label>
                  <textarea
                    className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono"
                    defaultValue={signature.html}
                    placeholder="<div>…</div>"
                    onBlur={(e) => {
                      if (e.target.value === signature.html) return
                      updateSignature.mutate({
                        signatureId: signature.id,
                        name: signature.name,
                        html: e.target.value,
                      })
                    }}
                  />
                </div>
                {signature.html?.trim() ? (
                  <div className="rounded-md border border-dashed border-border bg-muted/30 p-3 text-sm">
                    <p className="mb-2 text-xs text-muted-foreground">Aperçu</p>
                    <div
                      className="prose prose-sm max-w-none dark:prose-invert"
                      dangerouslySetInnerHTML={{ __html: signature.html }}
                    />
                  </div>
                ) : null}
              </li>
            ))}
          </ul>
        )}

        {showAddForm ? (
          <div className="rounded-lg border border-border p-3 space-y-3 max-w-2xl">
            <div className="space-y-1">
              <Label className="text-xs">Nom</Label>
              <Input
                value={draft.name}
                placeholder="Professionnelle"
                onChange={(e) => setDraft({ ...draft, name: e.target.value })}
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Contenu HTML</Label>
              <textarea
                className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono"
                value={draft.html}
                placeholder="<div style=&quot;color:#5f6368&quot;>…</div>"
                onChange={(e) => setDraft({ ...draft, html: e.target.value })}
              />
            </div>
            <div className="flex gap-2">
              <Button
                type="button"
                size="sm"
                disabled={createSignature.isPending || !draft.name.trim()}
                onClick={handleCreate}
              >
                Enregistrer
              </Button>
              <Button
                type="button"
                size="sm"
                variant="ghost"
                onClick={() => {
                  setShowAddForm(false)
                  setDraft({ name: "", html: "" })
                }}
              >
                Annuler
              </Button>
            </div>
          </div>
        ) : (
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => setShowAddForm(true)}
          >
            <Plus className="size-3.5 mr-1.5" />
            Ajouter une signature
          </Button>
        )}
      </CardContent>
    </Card>
  )
}
