import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Button } from '@heroui/react'
import { useSearchParams } from 'react-router-dom'
import {
  WORKFLOW_FIELD_TYPE,
  type WorkflowFileSelection,
  type WorkflowFormValues,
  type WorkflowParamMap,
  buildWorkflowParamMapAsync,
  createInitialWorkflowFileSelections,
  createInitialWorkflowFormValues,
  extractUploadUrlFromResponse,
  getWorkflowRequiredMissingFields,
  isWorkflowFieldFilled,
  parseWorkflowFormFields,
} from '../../lib/workflowCardForm'
import { CardWorkflowField } from './CardWorkflowField'
import { fetchUploadWorkflowFile } from '@/api/common'
import type { Answer, Attachment } from '@/types/chat'

interface CardWorkflowFormProps {
  attachment: Attachment
  answer: Answer
  onSubmitWorkflow: (paramMap: WorkflowParamMap, recordId?: string, workFlowSessionId?: string) => void
  isSubmitting?: boolean
  isCompleted?: boolean
}

export const CardWorkflowForm: React.FC<CardWorkflowFormProps> = ({
  attachment,
  answer,
  onSubmitWorkflow,
  isSubmitting = false,
  isCompleted = false,
}) => {
  const [formValues, setFormValues] = useState<WorkflowFormValues>({})
  const [fileSelections, setFileSelections] = useState<Record<string, WorkflowFileSelection | undefined>>({})
  const [uploadingFieldKey, setUploadingFieldKey] = useState<string | null>(null)
  const [submitAttempted, setSubmitAttempted] = useState(false)
  const [searchParams] = useSearchParams()
  const hasAutoSubmittedRef = useRef(false)
  const lastFirstQaFlagRef = useRef<boolean | undefined>(undefined)
  const onSubmitWorkflowRef = useRef(onSubmitWorkflow)

  useEffect(() => {
    onSubmitWorkflowRef.current = onSubmitWorkflow
  }, [onSubmitWorkflow])

  const workflowFields = useMemo(
    () => parseWorkflowFormFields(attachment),
    [attachment.content?.fieldList],
  )

  const missingRequiredFields = useMemo(
    () => getWorkflowRequiredMissingFields(workflowFields, formValues, fileSelections),
    [workflowFields, formValues, fileSelections],
  )

  const hasRequiredMissing = missingRequiredFields.length > 0

  useEffect(() => {
    setFormValues(createInitialWorkflowFormValues(workflowFields, {
      searchParams,
      useQueryPreset: answer.firstQaFlag === true,
    }))
    setFileSelections(createInitialWorkflowFileSelections(workflowFields))
    setSubmitAttempted(false)
  }, [workflowFields, searchParams, answer.firstQaFlag])

  useEffect(() => {
    if (answer.firstQaFlag !== true) {
      hasAutoSubmittedRef.current = false
      lastFirstQaFlagRef.current = false
    }
    else if (lastFirstQaFlagRef.current === undefined) {
      lastFirstQaFlagRef.current = false
    }
  }, [answer.firstQaFlag])

  const uploadWorkflowFile = async (file: File): Promise<string> => {
    const res = await fetchUploadWorkflowFile(file)
    const url = extractUploadUrlFromResponse(res?.data)
    if (!url)
      throw new Error('上传成功但未返回文件地址')
    return url
  }

  useEffect(() => {
    const isFirstQaFlagChangedToTrue = answer.firstQaFlag === true && lastFirstQaFlagRef.current !== true

    if (isFirstQaFlagChangedToTrue && !hasAutoSubmittedRef.current && !isSubmitting && !isCompleted) {
      if (workflowFields.length === 0) {
        lastFirstQaFlagRef.current = answer.firstQaFlag
        return
      }

      const requiredFields = workflowFields.filter(field => field.required)
      const allRequiredFieldsHaveValues = requiredFields.every(field =>
        isWorkflowFieldFilled(field, formValues[field.key], fileSelections[field.key]),
      )

      if (allRequiredFieldsHaveValues) {
        hasAutoSubmittedRef.current = true
        lastFirstQaFlagRef.current = answer.firstQaFlag

        const runAutoSubmit = async () => {
          const paramMap = await buildWorkflowParamMapAsync(
            workflowFields,
            formValues,
            fileSelections,
            uploadWorkflowFile,
          )
          onSubmitWorkflowRef.current(paramMap, answer.recordId, answer.workFlowSessionId)
        }

        const timeoutId = window.setTimeout(() => {
          void runAutoSubmit()
        }, 100)
        return () => window.clearTimeout(timeoutId)
      }

      lastFirstQaFlagRef.current = answer.firstQaFlag
    }
    else {
      lastFirstQaFlagRef.current = answer.firstQaFlag
    }
  }, [answer.firstQaFlag, isSubmitting, isCompleted, searchParams, workflowFields, formValues, fileSelections, answer.recordId, answer.workFlowSessionId, answer.conversationId])

  const handleFieldChange = (key: string, value: string | string[]) => {
    setFormValues(prev => ({
      ...prev,
      [key]: value,
    }))
  }

  const handlePickFile = async (key: string, file: File) => {
    setUploadingFieldKey(key)
    try {
      const url = await uploadWorkflowFile(file)
      setFileSelections(prev => ({
        ...prev,
        [key]: { fileName: file.name, file, fileUrls: [url] },
      }))
      setFormValues(prev => ({
        ...prev,
        [key]: file.name,
      }))
    }
    catch (error) {
      console.error('[CardWorkflowForm] 文件上传失败:', error)
    }
    finally {
      setUploadingFieldKey(null)
    }
  }

  const handleSubmit = async () => {
    setSubmitAttempted(true)
    if (hasRequiredMissing)
      return

    const paramMap = await buildWorkflowParamMapAsync(
      workflowFields,
      formValues,
      fileSelections,
      uploadWorkflowFile,
    )
    onSubmitWorkflow(paramMap, answer.recordId, answer.workFlowSessionId)
  }

  if (workflowFields.length === 0)
    return null

  if (answer.firstQaFlag === true && hasAutoSubmittedRef.current)
    return null

  const fieldDisabled = isSubmitting || isCompleted || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)
  const cardTitle = attachment.name?.trim()

  return (
    <div className="card-workflow-form">
      {cardTitle && (
        <div className="text-[15px] font-medium text-[#1f2937] mb-[12px]">{cardTitle}</div>
      )}
      <div className="flex flex-col gap-[12px]">
        {workflowFields.map((field) => {
          const showRequiredError = submitAttempted
            && field.required
            && !isWorkflowFieldFilled(field, formValues[field.key], fileSelections[field.key])

          return (
            <div key={field.key}>
              <CardWorkflowField
                field={field}
                value={formValues[field.key] ?? (field.type === WORKFLOW_FIELD_TYPE.SELECT && field.multiple ? [] : '')}
                onChange={handleFieldChange}
                onPickFile={handlePickFile}
                disabled={fieldDisabled || uploadingFieldKey === field.key}
                isUploading={uploadingFieldKey === field.key}
                showRequiredError={showRequiredError}
              />
            </div>
          )
        })}
        <Button
          color="primary"
          onPress={() => void handleSubmit()}
          isDisabled={fieldDisabled || uploadingFieldKey != null || (submitAttempted && hasRequiredMissing) || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)}
          isLoading={isSubmitting}
          className="mt-[8px]"
        >
          {isCompleted ? '已完成' : '提交'}
        </Button>
      </div>
    </div>
  )
}
