'use client'

import { useActionState, useState } from 'react'
import { MapPin } from 'lucide-react'
import { ImageDropzone } from '@/components/image-dropzone'
import { LocationMapPicker, type PickerMap } from '@/components/location-map-picker'
import { createItem } from '../actions'

const inputCls =
  'flex h-11 w-full rounded-lg border border-input bg-background px-3 py-2 text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'

interface Props {
  locations: { id: string; path: string }[]
  maps: PickerMap[]
}

export function AddItemForm({ locations, maps }: Props) {
  const [state, formAction, pending] = useActionState(createItem, null)
  const [locationId, setLocationId] = useState('')

  return (
    <form action={formAction} className="space-y-4">
      {state?.error && (
        <div className="bg-destructive/10 text-destructive text-sm rounded-lg px-4 py-3 border border-destructive/20">
          {state.error}
        </div>
      )}

      <ImageDropzone name="photo" label="Photo" />

      <Field label="Name">
        <input
          name="name"
          type="text"
          autoCapitalize="sentences"
          placeholder="e.g. Skidsteer loader"
          className={inputCls}
        />
      </Field>

      <Field label="Location" required>
        <div className="flex gap-2">
          <select
            name="locationId"
            required
            value={locationId}
            onChange={e => setLocationId(e.target.value)}
            className={inputCls + ' flex-1'}
          >
            <option value="" disabled>Choose a location…</option>
            {locations.map(l => (
              <option key={l.id} value={l.id}>{l.path}</option>
            ))}
          </select>
          <LocationMapPicker
            maps={maps}
            onPick={id => setLocationId(id)}
            trigger={
              <button
                type="button"
                className="h-11 px-3 rounded-lg border bg-card text-sm font-medium inline-flex items-center gap-1.5 hover:bg-accent/40"
                title="Pick on a map"
              >
                <MapPin className="size-4" />
                Map
              </button>
            }
          />
        </div>
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Quantity">
          <input name="qty" type="number" min={1} defaultValue={1} className={inputCls} />
        </Field>
        <Field label="Value">
          <input name="value" type="number" step="0.01" placeholder="0.00" className={inputCls} />
        </Field>
      </div>

      <Field label="Tags">
        <input
          name="tags"
          type="text"
          placeholder="comma-separated, e.g. tool, outdoor, heavy"
          autoCapitalize="none"
          className={inputCls}
        />
      </Field>

      <details className="rounded-lg border bg-card px-3 py-2">
        <summary className="text-sm font-medium cursor-pointer select-none py-1">More details</summary>
        <div className="mt-3 space-y-3 pb-2">
          <Field label="Category">
            <input name="category" type="text" placeholder="tool, appliance, etc." className={inputCls} />
          </Field>
          <Field label="Brand">
            <input name="brand" type="text" className={inputCls} />
          </Field>
          <Field label="Serial number">
            <input name="serialNumber" type="text" className={inputCls} />
          </Field>
          <Field label="Description">
            <textarea name="description" rows={2} className={inputCls + ' h-auto min-h-[2.75rem]'} />
          </Field>
          <Field label="Notes">
            <textarea name="notes" rows={3} className={inputCls + ' h-auto min-h-[2.75rem]'} />
          </Field>
        </div>
      </details>

      <button
        type="submit"
        disabled={pending}
        className="w-full h-11 rounded-lg bg-primary text-primary-foreground font-medium text-sm hover:bg-primary/90 transition-colors disabled:opacity-50"
      >
        {pending ? 'Saving…' : 'Save item'}
      </button>
    </form>
  )
}

function Field({
  label,
  required,
  children,
}: {
  label: string
  required?: boolean
  children: React.ReactNode
}) {
  return (
    <div className="space-y-1.5">
      <label className="text-sm font-medium">
        {label}
        {required && <span className="text-destructive"> *</span>}
      </label>
      {children}
    </div>
  )
}
