'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

type Decision = 'approve' | 'deny' | 'report'

/** Approve / Deny / Report — one decision, recorded with who made it (§18). */
export function DecisionForm({
  token,
  initialDecision,
  companyName,
}: {
  token: string
  initialDecision?: string
  companyName: string
}) {
  const router = useRouter()
  const [decision, setDecision] = useState<Decision | null>(
    initialDecision === 'approve' || initialDecision === 'deny' || initialDecision === 'report'
      ? initialDecision
      : null,
  )
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [busy, setBusy] = useState(false)

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!decision) return
    setBusy(true)
    try {
      const res = await fetch(`/api/company-claims/${token}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ decision, approver_name: name, approver_email: email }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(json.error ?? 'Could not record your decision')
        return
      }
      toast.success(
        decision === 'approve'
          ? 'Access approved'
          : decision === 'deny'
            ? 'Request denied'
            : 'Reported — HeavyHaul Agent will review this request',
      )
      router.refresh()
    } finally {
      setBusy(false)
    }
  }

  const options: Array<[Decision, string, string]> = [
    ['approve', 'Approve', `This person may represent ${companyName} in HeavyHaul Agent.`],
    ['deny', 'Deny', 'No access is granted.'],
    ['report', "I don't know this person", 'Sends the request to HeavyHaul Agent for review.'],
  ]

  return (
    <form onSubmit={submit} className="space-y-4">
      <div className="grid gap-2">
        {options.map(([value, label, help]) => (
          <button
            key={value}
            type="button"
            onClick={() => setDecision(value)}
            className={`rounded-xl border px-4 py-3 text-left transition ${
              decision === value
                ? value === 'approve'
                  ? 'border-green-600 bg-green-50'
                  : 'border-[#0f1b2d] bg-neutral-100'
                : 'bg-white hover:border-neutral-400'
            }`}
          >
            <span className="block text-sm font-bold">{label}</span>
            <span className="block text-xs text-neutral-500">{help}</span>
          </button>
        ))}
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        <div className="space-y-1.5">
          <Label htmlFor="approver-name">Your name</Label>
          <Input id="approver-name" value={name} onChange={(e) => setName(e.target.value)} required />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="approver-email">Your email</Label>
          <Input
            id="approver-email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
      </div>
      <p className="text-[11px] text-neutral-400">
        Your name, email, IP address and the time of this decision are recorded in the company&apos;s
        audit log.
      </p>
      <Button
        type="submit"
        disabled={!decision || busy}
        className="w-full bg-[#0f1b2d] font-bold hover:bg-[#1c2f4a]"
      >
        {busy ? 'Saving…' : 'Confirm decision'}
      </Button>
    </form>
  )
}
