import { useEffect, useState } from 'react'
import { useParams, Link } from 'react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm, type Resolver } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { apiFetch, apiFetchBlob } from '@/lib/api'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { ConfirmActionDialog } from '@/components/ui/confirm-action-dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useTheme } from '@/hooks/useTheme'
import { WORK_ORDER_STATUS_LABEL, workOrderStatusBadgeClass } from '@/lib/workOrderStatus'
import type { WorkOrderDetail, CatalogItem, Staff, Client, Vehicle } from '@/lib/types'

const CATEGORY_LABEL: Record<string, string> = {
  mao_de_obra:     'Mão de Obra',
  diagnostico:     'Diagnóstico',
  manutencao:      'Manutenção',
  pecas_mecanicas: 'Peças Mecânicas',
  pneus_jantes:    'Pneus / Jantes',
  eletrica:        'Elétrica / Eletrónica',
  fluidos:         'Fluidos / Óleos',
  ar_condicionado: 'Ar Condicionado',
  carrocaria:      'Carroçaria / Pintura',
  consumiveis:     'Consumíveis',
  acessorios:      'Acessórios',
  outro:           'Outro',
}

const TRANSITIONS: Record<string, string[]> = {
  quote:       ['open', 'cancelled'],
  open:        ['in_progress', 'cancelled'],
  in_progress: ['completed', 'cancelled'],
  completed:   ['invoiced', 'cancelled'],
  invoiced:    [],
  cancelled:   [],
}
const ETA_LABEL: Record<number, string> = {
  1: '1 dia',
  2: '2 dias',
  3: '3 dias',
  7: '7 dias',
  15: '15 dias',
  30: '30 dias',
  31: '+ de 30 dias',
}
const ETA_OPTIONS = [1, 2, 3, 7, 15, 30, 31]
const PAYMENT_METHOD_OPTIONS = [
  { value: 'numerario', label: 'Numerário' },
  { value: 'multibanco', label: 'Multibanco' },
  { value: 'transferencia_bancaria', label: 'Transferência Bancária' },
  { value: 'mb_way', label: 'MB WAY' },
  { value: 'cartao_debito', label: 'Cartão de Débito' },
  { value: 'cartao_credito', label: 'Cartão de Crédito' },
  { value: 'cheque', label: 'Cheque' },
  { value: 'outro', label: 'Outro' },
]
const PAYMENT_METHOD_LABEL: Record<string, string> = Object.fromEntries(PAYMENT_METHOD_OPTIONS.map((o) => [o.value, o.label]))

function formatDateSafe(value?: string | null, withTime = false): string {
  if (!value) return '—'
  const d = new Date(value)
  if (Number.isNaN(d.getTime())) return '—'
  return withTime
    ? new Intl.DateTimeFormat('pt-PT', { dateStyle: 'short', timeStyle: 'short' }).format(d)
    : new Intl.DateTimeFormat('pt-PT').format(d)
}

const metaSchema = z.object({
  client_id: z.string(),
  vehicle_id: z.string(),
  internal_notes: z.string(),
  client_notes: z.string(),
  eta_days: z.coerce.number().int(),
  real_deadline: z.string(),
  payment_method: z.string(),
  payment_date: z.string(),
})
type MetaForm = z.infer<typeof metaSchema>

// ─── Item form ────────────────────────────────────────────────────────────────

const itemSchema = z.object({
  catalog_item_id: z.string(),
  description:     z.string().min(1, 'Descrição obrigatória'),
  change_justification: z.string(),
  qty:             z.coerce.number().positive('Quantidade deve ser positiva'),
  unit_price:      z.coerce.number().min(0),
  discount_pct:    z.coerce.number().min(0).max(100),
})
type ItemForm = z.infer<typeof itemSchema>
const emptyItem: ItemForm = { catalog_item_id: '', description: '', change_justification: '', qty: 1, unit_price: 0, discount_pct: 0 }

// ─── Staff hours form ─────────────────────────────────────────────────────────

const shSchema = z.object({
  staff_id:      z.string().min(1, 'Seleccione um técnico'),
  hours:         z.coerce.number().positive('Horas deve ser positivo'),
  cost_per_hour: z.coerce.number().min(0),
})
type SHForm = z.infer<typeof shSchema>
const emptySH: SHForm = { staff_id: '', hours: 1, cost_per_hour: 0 }

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function WorkOrderDetailPage() {
  const { id } = useParams<{ id: string }>()
  const { theme } = useTheme('ui_theme', 'dark')
  const isLight = theme === 'light'
  const qc = useQueryClient()
  const [showAddItem, setShowAddItem] = useState(false)
  const [showAddStaff, setShowAddStaff] = useState(false)
  const [showMetaEdit, setShowMetaEdit] = useState(false)
  const [confirmAction, setConfirmAction] = useState<null | { type: 'cancel' | 'remove_item' | 'remove_staff'; id?: string }>(null)

  const { data: detail, isLoading, error: detailError } = useQuery<WorkOrderDetail>({
    queryKey: ['work-order', id],
    queryFn: () => apiFetch<WorkOrderDetail>(`/work-orders/${id}`),
  })

  const { data: catalogItems = [] } = useQuery<CatalogItem[]>({
    queryKey: ['catalog'],
    queryFn: () => apiFetch<CatalogItem[]>('/catalog'),
  })

  const { data: staffList = [] } = useQuery<Staff[]>({
    queryKey: ['staff'],
    queryFn: () => apiFetch<Staff[]>('/staff'),
  })
  const { data: invoices = [] } = useQuery<{ id: string; work_order_id: string; type: 'quote' | 'invoice'; issued_at: string }[]>({
    queryKey: ['invoices', 'work-order-detail'],
    queryFn: () => apiFetch('/invoices'),
  })
  const { data: clients = [] } = useQuery<Client[]>({
    queryKey: ['clients'],
    queryFn: () => apiFetch<Client[]>('/clients'),
  })
  const {
    register: regMeta,
    handleSubmit: handleMeta,
    watch: watchMeta,
    reset: resetMeta,
    formState: { errors: metaErrors },
  } = useForm<MetaForm>({
    resolver: zodResolver(metaSchema) as Resolver<MetaForm>,
    defaultValues: {
      client_id: '',
      vehicle_id: '',
      internal_notes: '',
      client_notes: '',
      eta_days: 1,
      real_deadline: '',
      payment_method: '',
      payment_date: '',
    },
  })
  const selectedMetaClient = watchMeta('client_id')
  const { data: vehicles = [] } = useQuery<Vehicle[]>({
    queryKey: ['vehicles', selectedMetaClient || detail?.client_id || '', 'wo-meta'],
    queryFn: () => apiFetch<Vehicle[]>(`/clients/${selectedMetaClient || detail?.client_id}/vehicles`),
    enabled: !!(selectedMetaClient || detail?.client_id),
  })

  // lookup maps
  const catalogMap = Object.fromEntries(catalogItems.map(c => [c.id, c]))
  const staffMap   = Object.fromEntries(staffList.map(s => [s.id, s]))

  // ── Transitions ──────────────────────────────────────────────────────────────

  const transition = useMutation({
    mutationFn: (status: string) => {
      if (status === 'invoiced') {
        return apiFetch('/invoices', {
          method: 'POST',
          body: JSON.stringify({ work_order_id: id, type: 'invoice' }),
        })
      }
      return apiFetch(`/work-orders/${id}/transition`, {
        method: 'POST',
        body: JSON.stringify({
          status,
          payment_method: '',
          payment_date: '',
        }),
      })
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['work-order', id] })
      qc.invalidateQueries({ queryKey: ['work-orders'] })
      qc.invalidateQueries({ queryKey: ['invoices'] })
    },
  })
  const updateMeta = useMutation({
    mutationFn: (data: MetaForm) =>
      apiFetch(`/work-orders/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
          ...data,
          real_deadline: detail?.status === 'quote' ? '' : data.real_deadline,
          payment_method: data.payment_method,
          payment_date: data.payment_date,
        }),
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['work-order', id] })
      qc.invalidateQueries({ queryKey: ['work-orders'] })
      setShowMetaEdit(false)
    },
  })

  // ── Items ─────────────────────────────────────────────────────────────────────

  const {
    register: regItem,
    handleSubmit: handleItem,
    setValue: setItemVal,
    reset: resetItem,
    formState: { errors: itemErrors },
  } = useForm<ItemForm>({
    resolver: zodResolver(itemSchema) as Resolver<ItemForm>,
    defaultValues: emptyItem,
  })

  function onCatalogSelect(e: React.ChangeEvent<HTMLSelectElement>) {
    const cid = e.target.value
    setItemVal('catalog_item_id', cid)
    if (cid) {
      const found = catalogMap[cid]
      if (found) {
        setItemVal('description', found.name)
        setItemVal('unit_price', found.base_price)
      }
    }
  }

  const addItem = useMutation({
    mutationFn: (data: ItemForm) =>
      apiFetch(`/work-orders/${id}/items`, { method: 'POST', body: JSON.stringify(data) }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['work-order', id] })
      setShowAddItem(false)
      resetItem(emptyItem)
    },
  })

  const removeItem = useMutation({
    mutationFn: (itemId: string) =>
      apiFetch(`/work-orders/${id}/items/${itemId}`, { method: 'DELETE' }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['work-order', id] }),
  })

  // ── Staff hours ───────────────────────────────────────────────────────────────

  const {
    register: regSH,
    handleSubmit: handleSH,
    setValue: setSHVal,
    reset: resetSH,
    formState: { errors: shErrors },
  } = useForm<SHForm>({
    resolver: zodResolver(shSchema) as Resolver<SHForm>,
    defaultValues: emptySH,
  })

  function onStaffSelect(e: React.ChangeEvent<HTMLSelectElement>) {
    const sid = e.target.value
    setSHVal('staff_id', sid)
    if (sid) {
      const found = staffMap[sid]
      if (found) setSHVal('cost_per_hour', found.hourly_rate)
    }
  }

  const addSH = useMutation({
    mutationFn: (data: SHForm) =>
      apiFetch(`/work-orders/${id}/staff-hours`, { method: 'POST', body: JSON.stringify(data) }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['work-order', id] })
      setShowAddStaff(false)
      resetSH(emptySH)
    },
  })

  const removeSH = useMutation({
    mutationFn: (shId: string) =>
      apiFetch(`/work-orders/${id}/staff-hours/${shId}`, { method: 'DELETE' }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['work-order', id] }),
  })

  useEffect(() => {
    if (!detail || showMetaEdit) return
    resetMeta({
      client_id: detail.client_id ?? '',
      vehicle_id: detail.vehicle_id ?? '',
      internal_notes: detail.internal_notes ?? '',
      client_notes: detail.client_notes ?? '',
      eta_days: detail.eta_days ?? 1,
      real_deadline: detail.real_deadline ? detail.real_deadline.split('T')[0] : '',
      payment_method: detail.payment_method ?? '',
      payment_date: detail.payment_date ? detail.payment_date.split('T')[0] : '',
    })
  }, [detail, showMetaEdit, resetMeta])

  // ── Render ────────────────────────────────────────────────────────────────────

  if (isLoading) return <p className="text-slate-400">A carregar...</p>
  if (detailError) return <p className="text-red-400">Erro ao abrir a ordem: {(detailError as Error).message}</p>
  if (!detail) return <p className="text-slate-400">Ordem não encontrada.</p>

  const items = Array.isArray(detail.items) ? detail.items : []
  const staffHours = Array.isArray(detail.staff_hours) ? detail.staff_hours : []
  const itemsTotal = items.reduce((s, i) => s + Number(i.total || 0), 0)
  const hoursTotal = staffHours.reduce((s, h) => s + Number(h.total || 0), 0)
  const nextStates = TRANSITIONS[detail.status] ?? []
  const editable   = detail.status !== 'invoiced' && detail.status !== 'cancelled'
  const clientName = detail.client_id ? (clients.find((c) => c.id === detail.client_id)?.name ?? '—') : '—'
  const woInvoices = invoices
    .filter((inv) => inv.work_order_id === detail.id)
    .sort((a, b) => new Date(b.issued_at).getTime() - new Date(a.issued_at).getTime())
  const preferredType = detail.status === 'invoiced' ? 'invoice' : 'quote'
  const selectedDoc = woInvoices.find((inv) => inv.type === preferredType) ?? woInvoices[0]

  async function openWOInvoicePDF() {
    if (!selectedDoc) return
    try {
      const blob = await apiFetchBlob(`/invoices/${selectedDoc.id}/pdf`)
      const url = URL.createObjectURL(blob)
      window.open(url, '_blank', 'noopener,noreferrer')
      setTimeout(() => URL.revokeObjectURL(url), 60_000)
    } catch {
      // transition/update errors already shown elsewhere
    }
  }
  const vehicleName = detail.vehicle_id
    ? (() => {
        const v = vehicles.find((it) => it.id === detail.vehicle_id)
        return v ? `${v.plate} — ${v.brand} ${v.model}` : '—'
      })()
    : '—'

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Link
          to="/app/work-orders"
          className={`text-sm ${isLight ? 'text-slate-600 hover:text-slate-900' : 'text-slate-400 hover:text-white'}`}
        >
          ← Ordens
        </Link>
        <span className={isLight ? 'text-slate-400' : 'text-slate-600'}>/</span>
        <h1 className={`text-2xl font-bold ${isLight ? 'text-slate-900' : 'text-white'}`}>Ordem #{detail.number}</h1>
        <Badge variant="outline" className={workOrderStatusBadgeClass(detail.status)}>
          {WORK_ORDER_STATUS_LABEL[detail.status]}
        </Badge>
        {selectedDoc && (
          <Button size="sm" variant="outline" onClick={openWOInvoicePDF}>
            Ver PDF
          </Button>
        )}
      </div>
      <section className={`rounded-lg border p-4 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700 bg-slate-900/50'}`}>
        <div className="grid gap-4 lg:grid-cols-3">
          <div className={`lg:col-span-2 rounded-md border p-3 ${isLight ? 'border-slate-300 bg-slate-50' : 'border-slate-800 bg-slate-950/40'}`}>
            <h2 className={`mb-3 text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Dados da OT</h2>
            <div className="grid gap-3 text-sm grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Cliente</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{clientName}</p>
              </div>
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Viatura</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{vehicleName}</p>
              </div>
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Criada em</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{formatDateSafe(detail.created_at, true)}</p>
              </div>
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Previsão de conclusão</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{ETA_LABEL[detail.eta_days] ?? `${detail.eta_days} dias`}</p>
              </div>
              {detail.status !== 'quote' && (
                <div>
                  <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Prazo real (deadline)</p>
                  <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{formatDateSafe(detail.real_deadline)}</p>
                </div>
              )}
              {(detail.status === 'completed' || detail.status === 'invoiced') && (
                <div>
                  <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Meio de pagamento</p>
                  <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{PAYMENT_METHOD_LABEL[detail.payment_method] ?? '—'}</p>
                </div>
              )}
              {(detail.status === 'completed' || detail.status === 'invoiced') && (
                <div>
                  <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Data de pagamento</p>
                  <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{formatDateSafe(detail.payment_date)}</p>
                </div>
              )}
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Observações</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{detail.client_notes || '—'}</p>
              </div>
              <div>
                <p className={isLight ? 'text-slate-500' : 'text-slate-500'}>Notas internas</p>
                <p className={isLight ? 'text-slate-800' : 'text-slate-200'}>{detail.internal_notes || '—'}</p>
              </div>
            </div>
          </div>

          <div className={`rounded-md border p-3 ${isLight ? 'border-slate-300 bg-slate-50' : 'border-slate-800 bg-slate-950/40'}`}>
            <div className="mb-3 flex items-center justify-between">
              <h3 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Editar Dados da OT</h3>
              {editable && !showMetaEdit && (
                <Button size="sm" onClick={() => setShowMetaEdit(true)}>Editar</Button>
              )}
            </div>
            {!showMetaEdit && editable && (
              <p className={`text-sm ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>Clique em editar para atualizar cliente, viatura, prazos e observações.</p>
            )}
            {!editable && (
              <p className={`text-sm ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>OT faturada/cancelada não permite edição.</p>
            )}
            {editable && showMetaEdit && (
              <form onSubmit={handleMeta((d) => updateMeta.mutate(d))} className="space-y-3">
                <div className="space-y-1">
                  <Label>Cliente</Label>
                  <select
                    {...regMeta('client_id')}
                    className={`w-full rounded-md border px-3 py-2 text-sm ${isLight ? 'border-slate-300 bg-white text-slate-900' : 'border-slate-600 bg-slate-900 text-white'}`}
                  >
                    <option value="">— Sem cliente —</option>
                    {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
                <div className="space-y-1">
                  <Label>Viatura</Label>
                  <select
                    {...regMeta('vehicle_id')}
                    className={`w-full rounded-md border px-3 py-2 text-sm ${isLight ? 'border-slate-300 bg-white text-slate-900' : 'border-slate-600 bg-slate-900 text-white'}`}
                  >
                    <option value="">— Sem viatura —</option>
                    {vehicles.map((v) => <option key={v.id} value={v.id}>{v.plate} — {v.brand} {v.model}</option>)}
                  </select>
                </div>
                <div className="space-y-1">
                  <Label>Previsão de conclusão</Label>
                  <select
                    {...regMeta('eta_days')}
                    className={`w-full rounded-md border px-3 py-2 text-sm ${isLight ? 'border-slate-300 bg-white text-slate-900' : 'border-slate-600 bg-slate-900 text-white'}`}
                  >
                    {ETA_OPTIONS.map((o) => <option key={o} value={o}>{ETA_LABEL[o]}</option>)}
                  </select>
                </div>
                {detail.status !== 'quote' && (
                  <div className="space-y-1">
                    <Label>Prazo real (deadline)</Label>
                    <Input
                      type="date"
                      {...regMeta('real_deadline')}
                      className={isLight ? 'bg-white border-slate-300 text-slate-900' : 'bg-slate-900 border-slate-600 text-white'}
                    />
                  </div>
                )}
                {(detail.status === 'completed' || detail.status === 'invoiced') && (
                  <div className="space-y-1">
                    <Label>Meio de pagamento</Label>
                    <select
                      {...regMeta('payment_method')}
                      className={`w-full rounded-md border px-3 py-2 text-sm ${isLight ? 'border-slate-300 bg-white text-slate-900' : 'border-slate-600 bg-slate-900 text-white'}`}
                    >
                      <option value="">— Selecionar —</option>
                      {PAYMENT_METHOD_OPTIONS.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}
                    </select>
                  </div>
                )}
                {(detail.status === 'completed' || detail.status === 'invoiced') && (
                  <div className="space-y-1">
                    <Label>Data de pagamento</Label>
                    <Input
                      type="date"
                      {...regMeta('payment_date')}
                      className={isLight ? 'bg-white border-slate-300 text-slate-900' : 'bg-slate-900 border-slate-600 text-white'}
                    />
                  </div>
                )}
                <div className="space-y-1">
                  <Label>Observações</Label>
                  <Input
                    {...regMeta('client_notes')}
                    className={isLight ? 'bg-white border-slate-300 text-slate-900' : 'bg-slate-900 border-slate-600 text-white'}
                  />
                </div>
                <div className="space-y-1">
                  <Label>Notas internas</Label>
                  <Input
                    {...regMeta('internal_notes')}
                    className={isLight ? 'bg-white border-slate-300 text-slate-900' : 'bg-slate-900 border-slate-600 text-white'}
                  />
                </div>
                {metaErrors.eta_days && <p className="text-red-400 text-sm">{metaErrors.eta_days.message}</p>}
                {updateMeta.error && <p className="text-red-400 text-sm">{(updateMeta.error as Error).message}</p>}
                <div className="flex justify-end gap-2">
                  <Button type="button" variant="outline" onClick={() => setShowMetaEdit(false)}>Cancelar</Button>
                  <Button type="submit" disabled={updateMeta.isPending}>
                    {updateMeta.isPending ? 'A guardar...' : 'Guardar alterações'}
                  </Button>
                </div>
              </form>
            )}
          </div>
        </div>
      </section>

      {/* Transitions */}
      {nextStates.length > 0 && (
        <div className="space-y-2">
          <div className="flex gap-2">
          <span className="text-slate-400 text-sm self-center">Transição:</span>
          {nextStates.map((s) => (
            <Button
              key={s}
              size="sm"
              variant={s === 'cancelled' ? 'destructive' : 'default'}
              onClick={() => {
                if (s === 'cancelled') {
                  setConfirmAction({ type: 'cancel' })
                  return
                }
                transition.mutate(s)
              }}
              disabled={transition.isPending}
            >
              → {WORK_ORDER_STATUS_LABEL[s as keyof typeof WORK_ORDER_STATUS_LABEL]}
            </Button>
          ))}
          </div>
          {transition.error && (
            <p className="text-sm text-red-400">{(transition.error as Error).message}</p>
          )}
        </div>
      )}

      {/* ── Items ─────────────────────────────────────────────────────────────── */}
      <section>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-white">Itens</h2>
          {editable && (
            <Button size="sm" onClick={() => { resetItem(emptyItem); setShowAddItem(true) }}>
              Adicionar Item
            </Button>
          )}
        </div>

        {showAddItem && (
          <div className="mb-4 bg-slate-800 rounded-lg border border-slate-700 p-4">
            <form onSubmit={handleItem((d) => addItem.mutate(d))} className="grid grid-cols-3 gap-3">
              <div className="col-span-3 space-y-1">
                <Label>Catálogo (opcional)</Label>
                <select
                  {...regItem('catalog_item_id')}
                  onChange={onCatalogSelect}
                  className="w-full rounded-md border border-slate-600 bg-slate-900 text-white px-3 py-2 text-sm"
                >
                  <option value="">— Seleccionar do catálogo —</option>
                  {catalogItems.filter(i => i.active).map(i => (
                    <option key={i.id} value={i.id}>
                      {i.code} — {i.name}
                    </option>
                  ))}
                </select>
              </div>
              <div className="col-span-3 space-y-1">
                <Label>Descrição *</Label>
                <Input {...regItem('description')} className="bg-slate-900 border-slate-600 text-white" />
                {itemErrors.description && <p className="text-red-400 text-xs">{itemErrors.description.message}</p>}
              </div>
              {detail.status === 'open' && (
                <div className="col-span-3 space-y-1">
                  <Label>Justificação da alteração *</Label>
                  <Input
                    {...regItem('change_justification')}
                    placeholder="Ex: Pedido do cliente para incluir peça adicional"
                    className="bg-slate-900 border-slate-600 text-white"
                  />
                  <p className="text-xs text-slate-500">Obrigatório em Orçamento Aprovado para garantir transparência.</p>
                </div>
              )}
              <div className="space-y-1">
                <Label>Qtd. *</Label>
                <Input type="number" step="0.001" {...regItem('qty')} className="bg-slate-900 border-slate-600 text-white" />
                {itemErrors.qty && <p className="text-red-400 text-xs">{itemErrors.qty.message}</p>}
              </div>
              <div className="space-y-1">
                <Label>Preço Unit. (€)</Label>
                <Input type="number" step="0.01" {...regItem('unit_price')} className="bg-slate-900 border-slate-600 text-white" />
              </div>
              <div className="space-y-1">
                <Label>Desconto (%)</Label>
                <Input type="number" step="0.01" {...regItem('discount_pct')} className="bg-slate-900 border-slate-600 text-white" />
              </div>
              {addItem.error && <p className="col-span-3 text-red-400 text-sm">{(addItem.error as Error).message}</p>}
              <div className="col-span-3 flex gap-2 justify-end">
                <Button type="button" variant="outline" size="sm" onClick={() => setShowAddItem(false)}>Cancelar</Button>
                <Button type="submit" size="sm" disabled={addItem.isPending}>
                  {addItem.isPending ? 'A adicionar...' : 'Adicionar'}
                </Button>
              </div>
            </form>
          </div>
        )}

        {items.length === 0 ? (
          <p className="text-slate-500 text-sm">Sem itens.</p>
        ) : (
          <div className="rounded-lg border border-slate-700 overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-slate-800">
                <tr>
                  <th className="text-left px-4 py-2 text-slate-400 font-medium">Artigo</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Qtd.</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Preço Unit.</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Desc.%</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Total</th>
                  <th className="px-4 py-2"></th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => {
                  const cat = item.catalog_item_id ? catalogMap[item.catalog_item_id] : null
                  return (
                    <tr key={item.id} className="border-t border-slate-700">
                      <td className="px-4 py-2">
                        <div className="text-white">{item.description}</div>
                        {cat && (
                          <div className="text-xs text-slate-500 mt-0.5">
                            {CATEGORY_LABEL[cat.category] ?? cat.category}
                          </div>
                        )}
                        {item.change_justification && (
                          <div className="text-xs text-amber-300/90 mt-1">
                            Justificação: {item.change_justification}
                          </div>
                        )}
                      </td>
                      <td className="px-4 py-2 text-slate-300 text-right">{item.qty}</td>
                      <td className="px-4 py-2 text-slate-300 text-right">{Number(item.unit_price || 0).toFixed(2)} €</td>
                      <td className="px-4 py-2 text-slate-300 text-right">{item.discount_pct}%</td>
                      <td className="px-4 py-2 text-white font-medium text-right">{Number(item.total || 0).toFixed(2)} €</td>
                      <td className="px-4 py-2 text-right">
                        {editable && (
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-400 hover:text-red-300 h-7 px-2"
                            onClick={() => setConfirmAction({ type: 'remove_item', id: item.id })}
                            disabled={removeItem.isPending}
                          >
                            ✕
                          </Button>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
              <tfoot className="bg-slate-800/50">
                <tr>
                  <td colSpan={4} className="px-4 py-2 text-slate-400 text-right font-medium">Subtotal itens</td>
                  <td className="px-4 py-2 text-white font-bold text-right">{itemsTotal.toFixed(2)} €</td>
                  <td />
                </tr>
                {hoursTotal > 0 && (
                  <tr>
                    <td colSpan={4} className="px-4 py-2 text-slate-400 text-right font-medium">Mão de obra</td>
                    <td className="px-4 py-2 text-white font-bold text-right">{hoursTotal.toFixed(2)} €</td>
                    <td />
                  </tr>
                )}
                <tr>
                  <td colSpan={4} className="px-4 py-2 text-slate-300 text-right font-bold">Total</td>
                  <td className="px-4 py-2 text-blue-400 font-bold text-right text-base">
                    {(itemsTotal + hoursTotal).toFixed(2)} €
                  </td>
                  <td />
                </tr>
              </tfoot>
            </table>
          </div>
        )}
      </section>

      {/* ── Staff hours ───────────────────────────────────────────────────────── */}
      <section>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-white">Técnicos</h2>
          {editable && (
            <Button size="sm" onClick={() => { resetSH(emptySH); setShowAddStaff(true) }}>
              Adicionar Técnico
            </Button>
          )}
        </div>

        {showAddStaff && (
          <div className="mb-4 bg-slate-800 rounded-lg border border-slate-700 p-4">
            <form onSubmit={handleSH((d) => addSH.mutate(d))} className="grid grid-cols-3 gap-3">
              <div className="col-span-3 space-y-1">
                <Label>Técnico *</Label>
                <select
                  {...regSH('staff_id')}
                  onChange={onStaffSelect}
                  className="w-full rounded-md border border-slate-600 bg-slate-900 text-white px-3 py-2 text-sm"
                >
                  <option value="">— Seleccionar técnico —</option>
                  {staffList.filter(s => s.active).map(s => (
                    <option key={s.id} value={s.id}>
                      {s.name} ({s.type === 'internal' ? 'Interno' : 'Externo'})
                    </option>
                  ))}
                </select>
                {shErrors.staff_id && <p className="text-red-400 text-xs">{shErrors.staff_id.message}</p>}
              </div>
              <div className="space-y-1">
                <Label>Horas *</Label>
                <Input type="number" step="0.25" {...regSH('hours')} className="bg-slate-900 border-slate-600 text-white" />
                {shErrors.hours && <p className="text-red-400 text-xs">{shErrors.hours.message}</p>}
              </div>
              <div className="space-y-1">
                <Label>€/hora</Label>
                <Input type="number" step="0.01" {...regSH('cost_per_hour')} className="bg-slate-900 border-slate-600 text-white" />
              </div>
              <div className="flex items-end pb-0.5">
                <p className="text-slate-500 text-xs">Preço preenchido automaticamente<br/>do cadastro do técnico</p>
              </div>
              {addSH.error && <p className="col-span-3 text-red-400 text-sm">{(addSH.error as Error).message}</p>}
              <div className="col-span-3 flex gap-2 justify-end">
                <Button type="button" variant="outline" size="sm" onClick={() => setShowAddStaff(false)}>Cancelar</Button>
                <Button type="submit" size="sm" disabled={addSH.isPending}>
                  {addSH.isPending ? 'A adicionar...' : 'Adicionar'}
                </Button>
              </div>
            </form>
          </div>
        )}

        {staffHours.length === 0 ? (
          <p className="text-slate-500 text-sm">Sem técnicos registados nesta ordem.</p>
        ) : (
          <div className="rounded-lg border border-slate-700 overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-slate-800">
                <tr>
                  <th className="text-left px-4 py-2 text-slate-400 font-medium">Técnico</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Horas</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">€/hora</th>
                  <th className="text-right px-4 py-2 text-slate-400 font-medium">Total</th>
                  <th className="px-4 py-2"></th>
                </tr>
              </thead>
              <tbody>
                {staffHours.map((sh) => {
                  const staff = staffMap[sh.staff_id]
                  return (
                    <tr key={sh.id} className="border-t border-slate-700">
                      <td className="px-4 py-2">
                        <div className="text-white">{staff?.name ?? '—'}</div>
                        {staff && (
                          <div className="text-xs text-slate-500 mt-0.5">
                            {staff.type === 'internal' ? 'Interno' : 'Externo'}
                          </div>
                        )}
                      </td>
                      <td className="px-4 py-2 text-white text-right">{sh.hours}</td>
                      <td className="px-4 py-2 text-slate-300 text-right">{Number(sh.cost_per_hour || 0).toFixed(2)} €</td>
                      <td className="px-4 py-2 text-white font-medium text-right">{Number(sh.total || 0).toFixed(2)} €</td>
                      <td className="px-4 py-2 text-right">
                        {editable && (
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-400 hover:text-red-300 h-7 px-2"
                            onClick={() => setConfirmAction({ type: 'remove_staff', id: sh.id })}
                            disabled={removeSH.isPending}
                          >
                            ✕
                          </Button>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
      <ConfirmActionDialog
        open={!!confirmAction}
        onOpenChange={(open) => !open && setConfirmAction(null)}
        title={
          confirmAction?.type === 'cancel'
            ? 'Cancelar ordem de trabalho'
            : confirmAction?.type === 'remove_item'
              ? 'Eliminar item'
              : 'Eliminar técnico'
        }
        description={
          confirmAction?.type === 'cancel'
            ? 'A ordem será marcada como cancelada e deixará de ser editável.'
            : confirmAction?.type === 'remove_item'
              ? 'Este item será removido da OT.'
              : 'Este registo de horas será removido da OT.'
        }
        confirmLabel={confirmAction?.type === 'cancel' ? 'Cancelar OT' : 'Eliminar'}
        pending={transition.isPending || removeItem.isPending || removeSH.isPending}
        onConfirm={() => {
          if (!confirmAction) return
          if (confirmAction.type === 'cancel') {
            transition.mutate('cancelled', {
              onSettled: () => setConfirmAction(null),
            })
            return
          }
          if (confirmAction.type === 'remove_item' && confirmAction.id) {
            removeItem.mutate(confirmAction.id, {
              onSettled: () => setConfirmAction(null),
            })
            return
          }
          if (confirmAction.type === 'remove_staff' && confirmAction.id) {
            removeSH.mutate(confirmAction.id, {
              onSettled: () => setConfirmAction(null),
            })
          }
        }}
      />
    </div>
  )
}
