'use client'

import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Input } from '@/components/ui/input'
import { roiEmailSchema, type ROIEmailInput } from '@/lib/validations/roiSchema'
import { ArrowRight, Loader2 } from 'lucide-react'
import type { ROIResults } from '@/types/roi'
import type { ROIInputs } from '@/types/roi'

interface ROIEmailCaptureProps {
  results: ROIResults
  inputs: ROIInputs
  onCaptured: () => void
}

export function ROIEmailCapture({ results, inputs, onCaptured }: ROIEmailCaptureProps) {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const form = useForm<ROIEmailInput>({
    resolver: zodResolver(roiEmailSchema),
  })

  const onSubmit = async (data: ROIEmailInput) => {
    setLoading(true)
    setError(null)

    try {
      const res = await fetch('/api/roi', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: data.email, results, inputs }),
      })

      if (!res.ok) throw new Error('Failed to submit')

      onCaptured()
    } catch {
      setError('Something went wrong. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div
      className="rounded-2xl p-6 mt-6"
      style={{
        background: 'rgba(99, 102, 241, 0.06)',
        border: '1px solid var(--dt-border-accent)',
      }}
    >
      <p className="text-sm font-semibold mb-1" style={{ color: 'var(--dt-text-primary)' }}>
        Get your personalized report
      </p>
      <p className="text-xs mb-4" style={{ color: 'var(--dt-text-secondary)' }}>
        Enter your email to unlock the full breakdown and receive your ROI summary.
      </p>

      <form onSubmit={form.handleSubmit(onSubmit)} className="flex gap-2">
        <Input
          {...form.register('email')}
          type="email"
          placeholder="your@email.com"
          className="flex-1 text-sm"
          style={{
            background: 'var(--dt-bg-elevated)',
            border: '1px solid var(--dt-border-glass)',
            color: 'var(--dt-text-primary)',
          }}
        />
        <button
          type="submit"
          disabled={loading}
          className="w-9 h-9 flex items-center justify-center rounded-lg text-white disabled:opacity-60 transition-opacity shrink-0"
          style={{ background: 'var(--dt-gradient-accent)' }}
        >
          {loading ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <ArrowRight className="w-4 h-4" />
          )}
        </button>
      </form>

      {form.formState.errors.email && (
        <p className="text-xs mt-2" style={{ color: '#fca5a5' }}>
          {form.formState.errors.email.message}
        </p>
      )}
      {error && (
        <p className="text-xs mt-2" style={{ color: '#fca5a5' }}>
          {error}
        </p>
      )}
    </div>
  )
}
