'use client'

import { useState, useTransition } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogClose,
} from '@/components/ui/dialog'
import { adminCreateProductAction, adminUpdateProductAction } from '@/actions/admin/products'

type User = { id: string; username: string }

type ProductData = {
  id: string
  name: string
  description: string | null
  repo_url: string | null
  definition_of_done: string
  auto_pr: boolean
  user_id: string
}

interface Props {
  mode: 'create' | 'edit'
  product?: ProductData
  allUsers: User[]
  trigger: React.ReactNode
}

export function ProductFormDialog({ mode, product, allUsers, trigger }: Props) {
  const [open, setOpen] = useState(false)
  const [pending, startTransition] = useTransition()
  const [error, setError] = useState<string | null>(null)

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const data = {
      name: fd.get('name') as string,
      description: fd.get('description') as string || undefined,
      repo_url: fd.get('repo_url') as string || undefined,
      definition_of_done: fd.get('definition_of_done') as string,
      auto_pr: fd.get('auto_pr') === 'on',
      owner_user_id: fd.get('owner_user_id') as string,
    }

    setError(null)
    startTransition(async () => {
      try {
        if (mode === 'create') {
          await adminCreateProductAction(data)
        } else {
          await adminUpdateProductAction(product!.id, data)
        }
        setOpen(false)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Onbekende fout')
      }
    })
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger render={<span />}>{trigger}</DialogTrigger>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{mode === 'create' ? 'Nieuw product' : 'Product bewerken'}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="space-y-1">
            <label htmlFor="name" className="text-sm font-medium">Naam</label>
            <Input id="name" name="name" required maxLength={100} defaultValue={product?.name} />
          </div>
          <div className="space-y-1">
            <label htmlFor="description" className="text-sm font-medium">Omschrijving</label>
            <Input id="description" name="description" defaultValue={product?.description ?? ''} />
          </div>
          <div className="space-y-1">
            <label htmlFor="repo_url" className="text-sm font-medium">Repo URL</label>
            <Input id="repo_url" name="repo_url" type="url" defaultValue={product?.repo_url ?? ''} placeholder="https://github.com/..." />
          </div>
          <div className="space-y-1">
            <label htmlFor="definition_of_done" className="text-sm font-medium">Definition of Done</label>
            <Input id="definition_of_done" name="definition_of_done" required defaultValue={product?.definition_of_done} />
          </div>
          {mode === 'create' && (
            <div className="space-y-1">
              <label htmlFor="owner_user_id" className="text-sm font-medium">Eigenaar</label>
              <select id="owner_user_id" name="owner_user_id" required className="w-full border border-border rounded-md px-2 py-1 text-sm bg-background text-foreground">
                {allUsers.map(u => (
                  <option key={u.id} value={u.id}>{u.username}</option>
                ))}
              </select>
            </div>
          )}
          {mode === 'edit' && (
            <input type="hidden" name="owner_user_id" value={product?.user_id} />
          )}
          <div className="flex items-center gap-2">
            <input id="auto_pr" name="auto_pr" type="checkbox" defaultChecked={product?.auto_pr} className="rounded border-border" />
            <label htmlFor="auto_pr" className="text-sm">Auto PR</label>
          </div>
          {error && (
            <div className="text-sm text-destructive bg-destructive/10 rounded px-3 py-2">{error}</div>
          )}
          <DialogFooter>
            <DialogClose render={<Button variant="outline" type="button" />}>Annuleer</DialogClose>
            <Button type="submit" disabled={pending}>
              {pending ? 'Opslaan…' : mode === 'create' ? 'Aanmaken' : 'Opslaan'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
