import React, { useEffect, useState } from 'react'
import { Card, Input, message } from 'antd'
import { useDispatch } from 'react-redux'
import apiClient from '../../services/apiClient'
import { updateDeviceRemark } from '../../store/slices/deviceSlice'

export interface DeviceInfoCardProps {
    device: {
        id?: string
        name?: string
        model?: string
        systemVersionName?: string
        osVersion?: string | number
        romType?: string
        romVersion?: string
        osBuildVersion?: string
        screenWidth?: number
        screenHeight?: number
        publicIP?: string
        remark?: string
        appName?: string
        appVersion?: string
        appPackage?: string
        connectedAt?: number
    }
}

export const DeviceInfoCard: React.FC<DeviceInfoCardProps> = ({ device }) => {
    const dispatch = useDispatch()
    const [editing, setEditing] = useState(false)
    const [draftRemark, setDraftRemark] = useState(device?.remark || '')
    const [saving, setSaving] = useState(false)

    useEffect(() => {
        setDraftRemark(device?.remark || '')
    }, [device?.remark])

    const saveRemarkIfChanged = async () => {
        if (!device?.id) return
        if ((device?.remark || '') === draftRemark) return
        setSaving(true)
        try {
            await apiClient.put(`/api/devices/${device.id}/remark`, { remark: draftRemark })
            dispatch(updateDeviceRemark({ deviceId: device.id, remark: draftRemark }))
            message.success('备注已更新')
        } catch (_e) {
            message.error('备注更新失败')
        } finally {
            setSaving(false)
            setEditing(false)
        }
    }
    return (
        <Card title="设备信息" size="default">
            <div style={{ fontSize: '18px', lineHeight: '1.6' }}>
                <div><strong>名称:</strong> {device?.name}</div>
                <div><strong>型号:</strong> {device?.model}</div>
                <div><strong>系统:</strong> {device?.systemVersionName ? `${device.systemVersionName} (${device.osVersion})` : `Android ${device?.osVersion ?? ''}`}</div>
                {device?.romType && device.romType !== '原生Android' && (
                    <div><strong>ROM:</strong> <span style={{ color: 'var(--md-primary)' }}>{device.romType}</span></div>
                )}
                {device?.romVersion && device.romVersion !== '未知版本' && (
                    <div><strong>ROM版本:</strong> <span style={{ color: 'var(--md-success)' }}>{device.romVersion}</span></div>
                )}
                {device?.osBuildVersion && (
                    <div><strong>系统版本号:</strong> <span style={{ color: 'var(--md-tertiary)' }}>{device.osBuildVersion}</span></div>
                )}
                <div><strong>分辨率:</strong> {device?.screenWidth}×{device?.screenHeight}</div>
                <div><strong>公网IP:</strong> {device?.publicIP || '未知'}</div>
                <div><strong>首次安装时间:</strong> {device?.connectedAt ? new Date(device.connectedAt).toLocaleString() : '未知'}</div>
                {(device?.appName || device?.appVersion || device?.appPackage) && (
                    <div style={{ marginTop: 6 }}>
                        {device?.appName && (<div><strong>APP名称:</strong> {device.appName}</div>)}
                        {device?.appVersion && (<div><strong>APP版本:</strong> {device.appVersion}</div>)}
                        {device?.appPackage && (<div><strong>APP包名:</strong> {device.appPackage}</div>)}
                    </div>
                )}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <strong style={{ marginRight: 4 }}>备注:</strong>
                    {editing ? (
                        <Input.TextArea
                            autoSize={{ minRows: 1, maxRows: 4 }}
                            value={draftRemark}
                            onChange={(e) => setDraftRemark(e.target.value)}
                            onBlur={saveRemarkIfChanged}
                            onPressEnter={(e) => {
                                if (e.ctrlKey || e.metaKey) {
                                    e.preventDefault()
                                    saveRemarkIfChanged()
                                }
                            }}
                            disabled={saving}
                            style={{ maxWidth: 360 }}
                            autoFocus
                        />
                    ) : (
                        <span
                            title={device?.remark || '点击编辑备注'}
                            style={{ cursor: 'pointer', maxWidth: 360, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
                            onClick={() => setEditing(true)}
                        >
                            {device?.remark || '点击编辑备注'}
                        </span>
                    )}
                </div>
         
            </div>
        </Card>
    )
}

export default DeviceInfoCard


