import { useState } from 'react'
import { Box, IconButton, TextField, Typography } from '@mui/material'
import { Pencil } from 'lucide-react'

interface Props {
  label: string
  value: string
  confidence?: number
  missing?: boolean
  onEdit?: (value: string) => void
}

export function ExtractedFieldRow({ label, value, missing = false, onEdit }: Props) {
  const [editing, setEditing] = useState(false)
  const [editValue, setEditValue] = useState(value)

  function commit() {
    setEditing(false)
    if (editValue !== value) onEdit?.(editValue)
  }

  if (editing) {
    return (
      <Box sx={{ py: 1, borderBottom: '1px solid #f1f5f9' }}>
        <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600, display: 'block', mb: 0.5 }}>
          {label}
        </Typography>
        <TextField
          size="small"
          fullWidth
          value={editValue}
          autoFocus
          onChange={e => setEditValue(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === 'Enter') commit() }}
        />
      </Box>
    )
  }

  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        gap: 1,
        py: 1,
        borderBottom: '1px solid #f1f5f9',
        opacity: missing ? 0.55 : 1,
        '&:hover .edit-btn': { visibility: 'visible' },
      }}
    >
      <Box sx={{ flex: 1 }}>
        <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 600, display: 'block' }}>
          {label}
        </Typography>
        <Typography variant="body2" sx={{ fontStyle: missing ? 'italic' : 'normal' }}>
          {value || '—'}
        </Typography>
      </Box>
      {onEdit && (
        <IconButton
          size="small"
          className="edit-btn"
          sx={{ visibility: 'hidden', p: 0.25, flexShrink: 0 }}
          onClick={() => { setEditValue(value); setEditing(true) }}
        >
          <Pencil size={12} />
        </IconButton>
      )}
    </Box>
  )
}
