import { useRef } from 'react'
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Stack,
  Box,
  Typography,
  IconButton,
  TextField,
  CircularProgress,
} from '@mui/material'
import CloseIcon from '@mui/icons-material/Close'
import UploadFileIcon from '@mui/icons-material/UploadFile'

interface CreateYamlDialogProps {
  open: boolean
  onClose: () => void
  onApply: (yaml: string) => void
  yamlContent: string
  onYamlChange: (value: string) => void
  loading: boolean
}

export default function CreateYamlDialog({
  open,
  onClose,
  onApply,
  yamlContent,
  onYamlChange,
  loading,
}: CreateYamlDialogProps) {
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target?.result as string
        onYamlChange(content)
      }
      reader.readAsText(file)
    }
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant="h6">创建资源</Typography>
          <IconButton onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <Box>
            <input
              ref={fileInputRef}
              type="file"
              accept=".yaml,.yml"
              style={{ display: 'none' }}
              onChange={handleFileUpload}
            />
            <Button
              variant="outlined"
              startIcon={<UploadFileIcon />}
              onClick={() => fileInputRef.current?.click()}
            >
              上传 YAML 文件
            </Button>
          </Box>
          <TextField
            label="YAML 内容"
            multiline
            rows={20}
            value={yamlContent}
            onChange={(e) => onYamlChange(e.target.value)}
            placeholder="粘贴或编辑 YAML 内容..."
            fullWidth
            variant="outlined"
          />
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          variant="contained"
          onClick={() => onApply(yamlContent)}
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} /> : '应用'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}
