import type {
  ImageOCRResponse,
  ImageOCRTextUpdateItem,
} from '../../service/type'
import type { CSSProperties } from 'react'
import { memo, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { Input } from '../ui/input'
import { Button } from '../ui/button'
import { cn } from '@/utils/cn'

import { Icon } from '../ui/icon'
import { Draggable } from './draggable'

export interface ImageTextEditorProps {
  className?: string
  ocrList: ImageOCRResponse
  onFinish?: () => void
  onConfirm?: (updatedList: ImageOCRTextUpdateItem[]) => void
  style?: CSSProperties
  measureRef?: (node: HTMLElement | null) => void
}

const MODAL_WIDTH = 520

function ImageTextEditor(props: ImageTextEditorProps) {
  const { className, ocrList, onFinish, onConfirm, style, measureRef } = props

  const [values, setValues] = useState<Record<string | number, string>>(() =>
    ocrList.reduce(
      (acc, item, index) => {
        acc[index] = item.line_text
        return acc
      },
      {} as Record<string | number, string>,
    ),
  )

  const handleOK = async () => {
    const updatedList: ImageOCRTextUpdateItem[] = []

    for (const key in values) {
      if (!Object.hasOwn(values, key)) continue
      const target = values[key]
      if (target !== ocrList[Number(key)].line_text) {
        const index = Number(key)
        const { line_rect: rect, line_text: source } = ocrList[index]
        updatedList.push({
          source,
          target,
          ...rect,
          w: rect.width,
          h: rect.height,
        })
      }
    }

    if (updatedList.length > 0) {
      onConfirm?.(updatedList)
    }

    onFinish?.()
  }

  const handleCancel = () => {
    onFinish?.()
  }

  return createPortal(
    <div className={cn('fixed inset-0 z-40 w-full h-full', className)}>
      <div
        className='fixed inset-0 bg-[rgba(15,28,36,0.08)]'
        onClick={handleCancel}
      />
      <Draggable
        innerRef={measureRef}
        className={cn(
          'image-text-editor-custom',
          'absolute z-50 flex flex-col rounded-[16px]',
          'editor-floating-panel pointer-events-auto',
        )}
        target='.modal-header'
        style={{
          ...style,
          width: MODAL_WIDTH,
        }}
      >
        {/* Header */}
        <div
          className='modal-header flex cursor-move select-none items-center justify-between border-0 border-b-[0.5px] border-solid px-[20px] py-[16px]'
          style={{ borderColor: 'var(--editor-border)' }}
        >
          <span className='text-[16px] font-600 text-foreground'>编辑文字</span>
          <div
            onClick={handleCancel}
            data-no-drag
            className='flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent'
          >
            <Icon icon='close' className='text-[18px]' />
          </div>
        </div>

        {/* Content */}
        {useMemo(
          () => (
            <div
              className='flex-1 p-[24px] overflow-y-auto overlay-scrollbar'
              style={{ maxHeight: '60vh' }}
            >
              <form
                id='image-text-editor-form'
                onSubmit={e => {
                  e.preventDefault()
                  handleOK()
                }}
              >
                {ocrList.map((ocr, index) => (
                  <div key={index} style={{ marginBottom: '16px' }}>
                    <Input
                      value={values[index] ?? ocr.line_text}
                      onChange={e =>
                        setValues(prev => {
                          if (prev[index] === e.target.value) return prev
                          return { ...prev, [index]: e.target.value }
                        })
                      }
                      placeholder={ocr.line_text}
                      className='h-[32px] border-border bg-secondary/60 px-[12px] focus:ring-1 focus:ring-primary/30'
                    />
                  </div>
                ))}
              </form>
            </div>
          ),
          [ocrList, values],
        )}

        {/* Footer */}
        <div
          className='flex items-center justify-end gap-[12px] rounded-b-16px border-0 border-t-[0.5px] border-solid px-[20px] py-[16px]'
          style={{
            borderColor: 'var(--editor-border)',
            background: 'var(--editor-surface-muted)',
          }}
        >
          <Button
            onClick={handleCancel}
            data-no-drag
            className='w-[100px]'
            variant='outline'
          >
            取消
          </Button>
          <Button
            className='w-[100px]'
            variant='default'
            onClick={handleOK}
            data-no-drag
          >
            确定修改
          </Button>
        </div>
      </Draggable>
    </div>,
    document.body,
  )
}

export default memo(ImageTextEditor)
