'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { PrimaryButton, SecondaryButton } from '@/app/FormFields'
import { useI18n } from '@/lib/i18n/client'

interface Props {
  ticketId: string
  version: number
}

export default function CloseTicketButton({ ticketId, version }: Props) {
  const { t } = useI18n()
  const router = useRouter()
  const [showConfirm, setShowConfirm] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleClose() {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`/api/tickets/${ticketId}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'CLOSED', version }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        setError(data.error ?? t('ticketDetail.closeButton.error'))
        setShowConfirm(false)
        return
      }
      router.refresh()
    } catch {
      setError(t('ticketDetail.closeButton.generic'))
      setShowConfirm(false)
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      <div className="space-y-1">
        <button
          type="button"
          onClick={() => setShowConfirm(true)}
          className="rounded-md border border-zinc-300 bg-white px-4 py-2 text-sm font-medium text-zinc-700 transition hover:bg-zinc-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800"
        >
          {t('ticketDetail.closeButton.label')}
        </button>
        {error ? <p className="text-xs text-red-600 dark:text-red-400">{error}</p> : null}
      </div>

      {showConfirm ? (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div
            role="dialog"
            aria-modal="true"
            aria-labelledby="close-ticket-confirm-title"
            className="w-full max-w-md rounded-lg border border-zinc-200 bg-white p-5 shadow-xl dark:border-zinc-700 dark:bg-zinc-900"
          >
            <h2 id="close-ticket-confirm-title" className="text-base font-semibold text-zinc-950 dark:text-white">
              {t('ticketDetail.closeButton.confirmTitle')}
            </h2>
            <p className="mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300">
              {t('ticketDetail.closeButton.confirmBody')}
            </p>
            <div className="mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
              <SecondaryButton
                type="button"
                disabled={loading}
                onClick={() => setShowConfirm(false)}
              >
                {t('ticketDetail.closeButton.confirmCancel')}
              </SecondaryButton>
              <PrimaryButton
                type="button"
                loading={loading}
                onClick={handleClose}
              >
                {t('ticketDetail.closeButton.confirmClose')}
              </PrimaryButton>
            </div>
          </div>
        </div>
      ) : null}
    </>
  )
}
