'use client'

import { useActionState } from 'react'
import { createTrip } from '@/app/trips/new/actions'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Alert, AlertDescription } from '@/components/ui/alert'

export function NewTripForm() {
  const [state, action, pending] = useActionState(createTrip, undefined)

  return (
    <form action={action} className="mt-6 space-y-5">
      {state?.error && (
        <Alert variant="destructive">
          <AlertDescription>{state.error}</AlertDescription>
        </Alert>
      )}
      <Card>
        <CardContent className="grid gap-4 pt-6 sm:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="origin">
              Origin <span className="text-red-600">*</span>
            </Label>
            <Input id="origin" name="origin" placeholder="Houston, TX" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="destination">
              Destination <span className="text-red-600">*</span>
            </Label>
            <Input id="destination" name="destination" placeholder="Chicago, IL" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="commodity">
              Commodity <span className="text-red-600">*</span>
            </Label>
            <Input id="commodity" name="commodity" placeholder="Excavator" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="carrier_name">Carrier</Label>
            <Input id="carrier_name" name="carrier_name" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="unit_number">Truck / unit number</Label>
            <Input id="unit_number" name="unit_number" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="pickup_date">Pickup date</Label>
            <Input id="pickup_date" name="pickup_date" type="date" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="delivery_date">Delivery date</Label>
            <Input id="delivery_date" name="delivery_date" type="date" />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="notes">Notes</Label>
            <Textarea id="notes" name="notes" rows={3} />
          </div>
        </CardContent>
      </Card>
      <Button type="submit" size="lg" className="w-full" disabled={pending}>
        {pending ? 'Creating…' : 'Create trip workspace'}
      </Button>
    </form>
  )
}
