'use client'

import { Button } from '@payloadcms/ui'
import { useSearchParams } from 'next/navigation'
import { useState } from 'react'

export function ExportButton() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const searchParams = useSearchParams()

  const handleExport = async () => {
    setLoading(true)
    setError(null)

    try {
      const exportParams = new URLSearchParams()
      const where = searchParams.get('where')

      if (where) {
        exportParams.set('where', where)
      }

      const endpoint = exportParams.size
        ? `/api/form-submissions-export?${exportParams.toString()}`
        : '/api/form-submissions-export'

      const response = await fetch(endpoint, {
        method: 'GET',
        credentials: 'include',
      })

      if (!response.ok) {
        let message = 'Failed to export submissions'
        try {
          const data = await response.json()
          if (data?.error) message = data.error
        } catch {}
        throw new Error(message)
      }

      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `form-submissions-${Date.now()}.csv`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (err) {
      const message = err instanceof Error ? err.message : 'An error occurred'
      setError(message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex justify-end mb-4 w-full">
      <Button buttonStyle="secondary" size="small" disabled={loading} onClick={handleExport}>
        {loading ? 'Exporting...' : 'Export to CSV'}
      </Button>

      {error && <p className="text-red-500 text-xs mt-2 w-full text-right">{error}</p>}
    </div>
  )
}
