import React, { useState } from 'react'
import {
  Box,
  Typography,
  Tabs,
  Tab,
  Stack,
  Chip,
  Button,
  ButtonGroup,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  CircularProgress,
  IconButton,
  Tooltip,
  Card,
  CardContent,
  useTheme,
} from '@mui/material'
import {
  Group as GroupIcon,
  Person as PersonIcon,
  CheckCircle as CheckCircleIcon,
  Cancel as CancelIcon,
  Refresh as RefreshIcon,
  Circle as CircleIcon,
  Sync as SyncIcon,
  ArrowBack as ArrowBackIcon,
} from '@mui/icons-material'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { chatChannelApi } from '../../../services/api/chat-channel'
import BasicInfo from './detail-tabs/BasicInfo'
import MessageHistory from './detail-tabs/MessageHistory'
import OverrideSettings from './detail-tabs/OverrideSettings'
import { CARD_VARIANTS } from '../../../theme/variants'
import { useMediaQuery } from '@mui/material'
import { useTranslation } from 'react-i18next'

interface ChatChannelDetailProps {
  chatKey: string
  onBack?: () => void
}

export default function ChatChannelDetail({ chatKey, onBack }: ChatChannelDetailProps) {
  const [currentTab, setCurrentTab] = useState(0)
  const [resetDialogOpen, setResetDialogOpen] = useState(false)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const queryClient = useQueryClient()
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('md'))
  const { t } = useTranslation('chat-channel')

  // 查询聊天详情
  const { data: channel, isLoading } = useQuery({
    queryKey: ['chat-channel-detail', chatKey],
    queryFn: () => chatChannelApi.getDetail(chatKey),
  })

  // 激活/停用聊天
  const { mutate: toggleActive, isPending: isToggling } = useMutation({
    mutationFn: (isActive: boolean) => chatChannelApi.setActive(chatKey, isActive),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['chat-channel-detail', chatKey] })
      queryClient.invalidateQueries({ queryKey: ['chat-channels'] })
    },
  })

  // 重置聊天
  const { mutate: resetChannel, isPending: isResetting } = useMutation({
    mutationFn: () => chatChannelApi.reset(chatKey),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['chat-channel-detail', chatKey] })
      setResetDialogOpen(false)
    },
  })

  // 刷新聊天信息
  const handleRefresh = async () => {
    setIsRefreshing(true)
    try {
      await queryClient.invalidateQueries({ queryKey: ['chat-channel-detail', chatKey] })
      await queryClient.invalidateQueries({ queryKey: ['chat-channels'] })
    } finally {
      setIsRefreshing(false)
    }
  }

  // 处理标签切换
  const handleTabChange = (_: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue)
  }

  if (isLoading || !channel) {
    return (
      <Card sx={{ ...CARD_VARIANTS.default.styles, height: '100%' }}>
        <Box className="h-full flex items-center justify-center">
          <CircularProgress />
        </Box>
      </Card>
    )
  }

  return (
    <Box className="h-full flex flex-col overflow-hidden gap-2">
      {/* 头部信息 */}
      <Card sx={CARD_VARIANTS.default.styles}>
        <CardContent sx={{ p: { xs: 1.5, md: 2 } }}>
          <Stack direction="row" spacing={2} alignItems="flex-start">
            {isMobile && onBack && (
              <IconButton onClick={onBack} edge="start">
                <ArrowBackIcon />
              </IconButton>
            )}
            {channel.chat_type === 'group' ? (
              <GroupIcon color="primary" sx={{ fontSize: 32, mt: 0.5 }} />
            ) : (
              <PersonIcon color="info" sx={{ fontSize: 32, mt: 0.5 }} />
            )}
            <Box className="flex-1 overflow-hidden">
              <Stack direction="row" spacing={1} alignItems="center">
                <Typography variant="h6" className="font-medium truncate">
                  {channel.channel_name || t('channelDetail.unnamedChat')}
                </Typography>
                <Tooltip title={t('channelDetail.refreshInfo')}>
                  <IconButton
                    size="small"
                    onClick={handleRefresh}
                    disabled={isRefreshing}
                    sx={{ mr: 0.5 }}
                  >
                    {isRefreshing ? <CircularProgress size={16} /> : <SyncIcon fontSize="small" />}
                  </IconButton>
                </Tooltip>
                <CircleIcon
                  sx={{
                    fontSize: 10,
                    color: channel.is_active ? 'success.main' : 'text.disabled',
                  }}
                />
              </Stack>
              <Typography
                variant="body2"
                color="textSecondary"
                sx={{ marginTop: 0.5, fontFamily: 'monospace', wordBreak: 'break-all' }}
              >
                {channel.chat_key}
              </Typography>
            </Box>
            <Stack spacing={1} alignItems="flex-end" sx={{ flexShrink: 0 }}>
              <Chip
                size="small"
                icon={channel.chat_type === 'group' ? <GroupIcon /> : <PersonIcon />}
                label={
                  channel.chat_type === 'group'
                    ? t('channelDetail.group')
                    : t('channelDetail.private')
                }
                color={channel.chat_type === 'group' ? 'primary' : 'info'}
                variant="outlined"
              />
              <ButtonGroup variant="outlined" size="small">
                <Button
                  color={channel.is_active ? 'error' : 'success'}
                  onClick={() => toggleActive(!channel.is_active)}
                  disabled={isToggling}
                  startIcon={channel.is_active ? <CancelIcon /> : <CheckCircleIcon />}
                >
                  {isToggling ? (
                    <CircularProgress size={16} />
                  ) : channel.is_active ? (
                    t('channelDetail.deactivate')
                  ) : (
                    t('channelDetail.activate')
                  )}
                </Button>
                <Button
                  color="warning"
                  onClick={() => setResetDialogOpen(true)}
                  startIcon={<RefreshIcon />}
                >
                  {t('channelDetail.reset')}
                </Button>
              </ButtonGroup>
            </Stack>
          </Stack>
        </CardContent>
      </Card>

      {/* 标签页 */}
      <Card sx={CARD_VARIANTS.default.styles}>
        <Tabs
          value={currentTab}
          onChange={handleTabChange}
          variant="fullWidth"
          sx={{
            minHeight: 56,
            '& .MuiTab-root': {
              minHeight: 56,
              fontSize: '0.875rem',
              fontWeight: 600,
              textTransform: 'none',
            },
          }}
        >
          <Tab label={t('channelDetail.tabs.basicInfo')} />
          <Tab label={t('channelDetail.tabs.overrideSettings')} />
          <Tab label={t('channelDetail.tabs.messageHistory')} />
        </Tabs>
      </Card>

      {/* 标签内容 */}
      <Box className="flex-1 overflow-hidden">
        {currentTab === 0 && (
          <Card sx={{ ...CARD_VARIANTS.default.styles, height: '100%', overflow: 'auto' }}>
            <BasicInfo channel={channel} />
          </Card>
        )}
        {currentTab === 1 && (
          <Card sx={{ ...CARD_VARIANTS.default.styles, height: '100%', overflow: 'auto' }}>
            <OverrideSettings chatKey={chatKey} />
          </Card>
        )}
        {currentTab === 2 && (
          <Card sx={{ ...CARD_VARIANTS.default.styles, height: '100%', p: 0, overflow: 'hidden' }}>
            <MessageHistory chatKey={chatKey} />
          </Card>
        )}
      </Box>

      {/* 重置确认对话框 */}
      <Dialog open={resetDialogOpen} onClose={() => setResetDialogOpen(false)}>
        <DialogTitle>{t('channelDetail.resetDialog.title')}</DialogTitle>
        <DialogContent>
          <Typography>{t('channelDetail.resetDialog.content')}</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setResetDialogOpen(false)}>
            {t('channelDetail.resetDialog.cancel')}
          </Button>
          <Button onClick={() => resetChannel()} color="warning" disabled={isResetting}>
            {isResetting ? <CircularProgress size={20} /> : t('channelDetail.resetDialog.confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}
