import { useEffect, useState } from 'react'
import { v4 as uuidv4 } from 'uuid'
import { Check } from 'lucide-react'
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { RESOURCE_TYPE_LABELS } from './resource-types'
import type { Resource, ResourceType } from '@/domain/types'

interface ResourceFormState {
  name: string
  type: ResourceType
  costPerHour: string
}

const EMPTY_FORM: ResourceFormState = { name: '', type: 'role', costPerHour: '' }

interface ResourceFormSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  resource?: Resource
  onSave: (resource: Resource) => Promise<void>
}

export function ResourceFormSheet({ open, onOpenChange, resource, onSave }: ResourceFormSheetProps) {
  const [form, setForm] = useState<ResourceFormState>(EMPTY_FORM)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    if (open) {
      setForm(
        resource
          ? { name: resource.name, type: resource.type, costPerHour: resource.costPerHour.toString() }
          : EMPTY_FORM
      )
    }
  }, [open, resource])

  async function handleSubmit() {
    if (!form.name.trim()) return
    setSaving(true)
    try {
      await onSave({
        id: resource?.id ?? uuidv4(),
        name: form.name.trim(),
        type: form.type,
        costPerHour: parseFloat(form.costPerHour) || 0,
      })
      onOpenChange(false)
    } finally {
      setSaving(false)
    }
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>{resource ? 'Editar recurso' : 'Nuevo recurso'}</SheetTitle>
        </SheetHeader>

        <div className="space-y-4 mt-6">
          <div className="space-y-1.5">
            <Label className="text-xs">Nombre</Label>
            <Input
              autoFocus
              placeholder="ej. Analista Senior"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs">Tipo</Label>
            <Select value={form.type} onValueChange={(v) => setForm((f) => ({ ...f, type: v as ResourceType }))}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {(Object.entries(RESOURCE_TYPE_LABELS) as [ResourceType, string][]).map(([value, label]) => (
                  <SelectItem key={value} value={value}>{label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs">Costo por hora</Label>
            <Input
              type="number"
              min={0}
              step={5}
              placeholder="0.00"
              value={form.costPerHour}
              onChange={(e) => setForm((f) => ({ ...f, costPerHour: e.target.value }))}
              className="font-mono"
            />
          </div>
        </div>

        <SheetFooter className="mt-6">
          <Button onClick={handleSubmit} disabled={!form.name.trim() || saving} className="gap-1.5">
            <Check className="h-4 w-4" />
            {resource ? 'Actualizar' : 'Crear'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}
