'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Label } from '@/components/ui/label'

/**
 * Broker default permit-handling rules (order-intake doc §22-23). The
 * defaults preselect (and hard-lock, when not 'ask') the broker's Create
 * Trip Request form AND control which paths carriers see on the public
 * intake page.
 */
export function BrokerDefaults({
  initialPolicy,
  initialPayment,
}: {
  initialPolicy: 'synchron_required' | 'upload_allowed' | 'ask'
  initialPayment: 'broker' | 'carrier' | 'ask'
}) {
  const [policy, setPolicy] = useState(initialPolicy)
  const [payment, setPayment] = useState(initialPayment)
  const [saving, setSaving] = useState(false)

  async function save() {
    setSaving(true)
    try {
      const res = await fetch('/api/broker/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ default_permit_policy: policy, default_payment_party: payment }),
      })
      const json = await res.json()
      if (!res.ok) toast.error(json.error ?? 'Could not save')
      else toast.success('Defaults saved — they now drive your order form and intake page')
    } finally {
      setSaving(false)
    }
  }

  const policyOptions = [
    ['ask', 'Let me choose per trip'],
    ['upload_allowed', 'Allow carriers to upload their own permits'],
    ['synchron_required', 'Require Synchron Permits for all loads'],
  ] as const
  const paymentOptions = [
    ['ask', 'Let me choose per trip'],
    ['broker', 'Broker pays by default'],
    ['carrier', 'Carrier pays by default'],
  ] as const

  return (
    <Card className="mt-6">
      <CardContent className="space-y-4 pt-6">
        <div>
          <h2 className="text-sm font-bold uppercase tracking-wide text-neutral-500">
            Permit handling defaults
          </h2>
          <p className="mt-1 text-xs text-neutral-500">
            These defaults preselect your Create Trip Request form and control which options
            carriers see on your intake page.
          </p>
        </div>
        <div className="space-y-1.5">
          <Label>Default permit handling</Label>
          <select
            value={policy}
            onChange={(e) => setPolicy(e.target.value as typeof policy)}
            className="w-full rounded-lg border px-3 py-2 text-sm"
          >
            {policyOptions.map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </select>
        </div>
        <div className="space-y-1.5">
          <Label>Default payment responsibility (Synchron orders)</Label>
          <select
            value={payment}
            onChange={(e) => setPayment(e.target.value as typeof payment)}
            className="w-full rounded-lg border px-3 py-2 text-sm"
          >
            {paymentOptions.map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </select>
        </div>
        <Button size="sm" onClick={save} disabled={saving}>
          {saving ? 'Saving…' : 'Save defaults'}
        </Button>
      </CardContent>
    </Card>
  )
}
