import React, { useState } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  CardActionArea,
  Grid,
  Chip,
  useTheme,
  alpha,
  Divider,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Alert,
  Snackbar,
} from '@mui/material';
import {
  Computer as ComputerIcon,
  Tablet as TabletIcon,
  PhoneAndroid as PhoneIcon,
  Check as CheckIcon,
  Close as CloseIcon,
  Visibility as VisibilityIcon,
  OpenInNew as OpenInNewIcon,
  Person as PersonIcon,
  PersonOutline as PersonOutlineIcon,
  Save as SaveIcon,
  Undo as UndoIcon,
} from '@mui/icons-material';
import { useUITheme, UIThemeId, DeviceType, UIThemeInfo } from '../../contexts/UIThemeContext';
import { useAuth } from '../../contexts/AuthContext';

// 디바이스 아이콘 매핑
const getDeviceIcon = (device: DeviceType) => {
  switch (device) {
    case 'pc':
      return <ComputerIcon />;
    case 'tablet':
      return <TabletIcon />;
    case 'mobile':
      return <PhoneIcon />;
    default:
      return <ComputerIcon />;
  }
};

// 디바이스 이름 매핑
const getDeviceName = (device: DeviceType) => {
  switch (device) {
    case 'pc':
      return 'PC (데스크톱)';
    case 'tablet':
      return '태블릿';
    case 'mobile':
      return '모바일';
    default:
      return device;
  }
};

// 테마 미리보기 모달 컴포넌트
interface ThemePreviewModalProps {
  open: boolean;
  onClose: () => void;
  theme: UIThemeInfo | null;
}

interface ThemePreviewModalProps {
  open: boolean;
  onClose: () => void;
  theme: UIThemeInfo | null;
  onApply?: () => void;
  isApplied?: boolean;
}

const ThemePreviewModal: React.FC<ThemePreviewModalProps> = ({ open, onClose, theme, onApply, isApplied }) => {
  const muiTheme = useTheme();
  const isDark = muiTheme.palette.mode === 'dark';
  const [loading, setLoading] = useState(true);

  if (!theme) return null;

  const badgeColor = theme.deviceType === 'pc' 
    ? { bg: 'rgba(59, 130, 246, 0.2)', color: '#60a5fa' }
    : theme.deviceType === 'tablet' 
      ? { bg: 'rgba(139, 92, 246, 0.2)', color: '#a78bfa' }
      : { bg: 'rgba(34, 197, 94, 0.2)', color: '#4ade80' };

  return (
    <Dialog 
      open={open} 
      onClose={onClose} 
      maxWidth="lg" 
      fullWidth
      PaperProps={{
        sx: {
          bgcolor: isDark ? '#1a1a2e' : '#fff',
          height: '85vh',
        }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        bgcolor: '#1976d2',
        color: '#fff',
        py: 1.2,
      }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Chip 
            label={theme.badgeCode} 
            size="small"
            sx={{ bgcolor: 'rgba(255,255,255,0.2)', color: '#fff' }}
          />
          <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
            {theme.name}
          </Typography>
          {isApplied && (
            <Chip label="현재 적용중" size="small" sx={{ bgcolor: 'rgba(255,255,255,0.2)', color: '#fff' }} />
          )}
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          {theme.mockupUrl && (
            <IconButton 
              onClick={() => window.open(theme.mockupUrl, '_blank')}
              title="새 창에서 열기"
              size="small"
              sx={{ color: '#fff' }}
            >
              <OpenInNewIcon />
            </IconButton>
          )}
          <IconButton onClick={onClose} size="small" sx={{ color: '#fff' }}>
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
      <DialogContent sx={{ p: 0, overflow: 'hidden', position: 'relative' }}>
        {loading && theme.mockupUrl && (
          <Box sx={{ 
            position: 'absolute', 
            inset: 0, 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            bgcolor: isDark ? '#0f0f23' : '#f5f5f5',
            zIndex: 1,
          }}>
            <Typography color="text.secondary">로딩 중...</Typography>
          </Box>
        )}
        {theme.mockupUrl ? (
          <iframe
            src={theme.mockupUrl}
            style={{
              width: '100%',
              height: '100%',
              border: 'none',
            }}
            title={`${theme.name} 미리보기`}
            onLoad={() => setLoading(false)}
          />
        ) : (
          <Box sx={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center', 
            height: '100%',
            flexDirection: 'column',
            gap: 2,
            bgcolor: isDark ? '#0f0f23' : '#f5f5f5',
          }}>
            <Box sx={{ 
              p: 4, 
              borderRadius: 2, 
              bgcolor: theme.style.backgroundColor,
              border: `1px solid ${theme.style.borderColor}`,
              textAlign: 'center',
              minWidth: 300,
            }}>
              <Typography sx={{ color: theme.style.textColor, fontWeight: 600, mb: 1 }}>
                기본 테마 미리보기
              </Typography>
              <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center', mb: 2 }}>
                <Box sx={{ width: 40, height: 40, borderRadius: 1, bgcolor: theme.style.primaryColor }} />
                <Box sx={{ width: 40, height: 40, borderRadius: 1, bgcolor: theme.style.accentColor }} />
                <Box sx={{ width: 40, height: 40, borderRadius: 1, bgcolor: theme.style.surfaceColor, border: `1px solid ${theme.style.borderColor}` }} />
              </Box>
              <Typography variant="caption" sx={{ color: theme.style.textSecondaryColor }}>
                Primary / Accent / Surface
              </Typography>
            </Box>
          </Box>
        )}
      </DialogContent>
      <DialogActions sx={{ 
        borderTop: `1px solid ${isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'}`,
        p: 2,
        gap: 1,
      }}>
        <Typography variant="body2" color="text.secondary" sx={{ flex: 1 }}>
          {theme.description}
        </Typography>
        {onApply && !isApplied && (
          <Button 
            variant="contained" 
            startIcon={<CheckIcon />}
            onClick={() => {
              onApply();
              onClose();
            }}
          >
            이 테마 선택
          </Button>
        )}
        <Button onClick={onClose} variant="outlined">닫기</Button>
      </DialogActions>
    </Dialog>
  );
};

// 테마 카드 컴포넌트
interface ThemeCardProps {
  theme: UIThemeInfo;
  isSelected: boolean;
  isCurrentApplied: boolean;
  onSelect: () => void;
  onPreview: () => void;
}

const ThemeCard: React.FC<ThemeCardProps> = ({ 
  theme, 
  isSelected, 
  isCurrentApplied,
  onSelect, 
  onPreview 
}) => {
  const muiTheme = useTheme();
  const isDark = muiTheme.palette.mode === 'dark';

  const badgeColor = theme.deviceType === 'pc' 
    ? { bg: 'rgba(59, 130, 246, 0.2)', color: '#60a5fa' }
    : theme.deviceType === 'tablet' 
      ? { bg: 'rgba(139, 92, 246, 0.2)', color: '#a78bfa' }
      : { bg: 'rgba(34, 197, 94, 0.2)', color: '#4ade80' };

  return (
    <Card
      sx={{
        border: isSelected
          ? `2px solid ${muiTheme.palette.primary.main}`
          : isCurrentApplied
            ? `2px solid ${muiTheme.palette.success.main}`
            : `1px solid ${isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'}`,
        bgcolor: isSelected
          ? alpha(muiTheme.palette.primary.main, 0.05)
          : isCurrentApplied
            ? alpha(muiTheme.palette.success.main, 0.03)
            : 'background.paper',
        transition: 'all 0.2s ease',
        position: 'relative',
        '&:hover': {
          borderColor: muiTheme.palette.primary.main,
          boxShadow: `0 4px 12px ${alpha(muiTheme.palette.primary.main, 0.2)}`,
        },
      }}
    >
      {/* 현재 적용 중 표시 */}
      {isCurrentApplied && !isSelected && (
        <Chip
          label="현재 적용"
          size="small"
          color="success"
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            zIndex: 1,
            fontSize: '10px',
            height: 20,
          }}
        />
      )}
      
      {/* 미리보기 영역 */}
      <Box 
        sx={{ 
          height: 140, 
          position: 'relative', 
          overflow: 'hidden',
          bgcolor: theme.style.backgroundColor,
          cursor: 'pointer',
          '&:hover .preview-overlay': {
            opacity: 1,
          },
        }}
        onClick={(e) => {
          e.stopPropagation();
          onPreview();
        }}
      >
        {theme.mockupUrl ? (
          <>
            <iframe
              src={theme.mockupUrl}
              style={{
                width: '300%',
                height: '300%',
                border: 'none',
                transform: 'scale(0.333)',
                transformOrigin: 'top left',
                pointerEvents: 'none',
              }}
              title={theme.name}
            />
            <Box 
              sx={{ 
                position: 'absolute', 
                inset: 0,
                background: 'linear-gradient(180deg, transparent 40%, rgba(15, 15, 35, 0.95) 100%)',
              }} 
            />
          </>
        ) : (
          <Box sx={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center', 
            height: '100%',
            flexDirection: 'column',
            gap: 1,
          }}>
            {/* 색상 미리보기 */}
            <Box sx={{ display: 'flex', gap: 0.5 }}>
              <Box sx={{ width: 24, height: 24, borderRadius: '50%', bgcolor: theme.style.primaryColor }} />
              <Box sx={{ width: 24, height: 24, borderRadius: '50%', bgcolor: theme.style.accentColor }} />
              <Box sx={{ width: 24, height: 24, borderRadius: '50%', bgcolor: theme.style.surfaceColor, border: `1px solid ${theme.style.borderColor}` }} />
            </Box>
            <Typography sx={{ color: theme.style.textSecondaryColor, fontSize: '11px' }}>
              기본 테마
            </Typography>
          </Box>
        )}
        
        {/* 미리보기 오버레이 */}
        <Box 
          className="preview-overlay"
          sx={{ 
            position: 'absolute', 
            inset: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            bgcolor: 'rgba(0,0,0,0.6)',
            opacity: 0,
            transition: 'opacity 0.2s ease',
          }}
        >
          <Box sx={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: 1, 
            color: '#fff',
            bgcolor: 'rgba(0,0,0,0.5)',
            px: 2,
            py: 1,
            borderRadius: 2,
          }}>
            <VisibilityIcon fontSize="small" />
            <Typography fontSize="13px" fontWeight={500}>미리보기</Typography>
          </Box>
        </Box>
      </Box>

      <CardActionArea onClick={onSelect}>
        <CardContent sx={{ p: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Chip 
                label={theme.badgeCode} 
                size="small"
                sx={{ 
                  bgcolor: badgeColor.bg,
                  color: badgeColor.color,
                  fontSize: '10px',
                  height: 20,
                }}
              />
              <Typography variant="subtitle2" fontWeight={600}>
                {theme.name}
              </Typography>
            </Box>
            {isSelected && (
              <CheckIcon sx={{ color: 'primary.main', fontSize: 18 }} />
            )}
          </Box>
          
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5, minHeight: 36, fontSize: '12px' }}>
            {theme.description}
          </Typography>
          
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
            {theme.tags.map((tag, i) => (
              <Chip 
                key={i} 
                label={tag} 
                size="small"
                sx={{ 
                  fontSize: '10px', 
                  height: 18,
                  bgcolor: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)',
                }}
              />
            ))}
          </Box>
        </CardContent>
      </CardActionArea>
    </Card>
  );
};

// 디바이스별 테마 설정 섹션
interface DeviceThemeSectionProps {
  device: DeviceType;
  selectedThemeId: UIThemeId;
  currentAppliedThemeId: UIThemeId;
  availableThemes: UIThemeInfo[];
  onThemeSelect: (themeId: UIThemeId) => void;
  onThemePreview: (theme: UIThemeInfo, device: DeviceType) => void;
}

const DeviceThemeSection: React.FC<DeviceThemeSectionProps> = ({
  device,
  selectedThemeId,
  currentAppliedThemeId,
  availableThemes,
  onThemeSelect,
  onThemePreview,
}) => {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const { currentDevice } = useUITheme();
  const isCurrentDevice = currentDevice === device;

  return (
    <Box sx={{ mb: 4 }}>
      <Box sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        gap: 1.5, 
        mb: 2,
        pb: 1,
        borderBottom: `1px solid ${isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'}`,
      }}>
        <Box sx={{ 
          display: 'flex', 
          alignItems: 'center', 
          color: isCurrentDevice ? 'primary.main' : 'text.secondary',
        }}>
          {getDeviceIcon(device)}
        </Box>
        <Typography variant="h6" fontWeight={600}>
          {getDeviceName(device)}
        </Typography>
        {isCurrentDevice && (
          <Chip 
            label="현재 디바이스" 
            size="small" 
            color="primary" 
            variant="outlined"
            sx={{ height: 24, fontSize: '11px' }}
          />
        )}
        <Typography variant="caption" color="text.secondary" sx={{ ml: 'auto' }}>
          {availableThemes.length}개 테마
        </Typography>
      </Box>

      <Grid container spacing={2}>
        {availableThemes.map((themeInfo) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={themeInfo.id}>
            <ThemeCard
              theme={themeInfo}
              isSelected={selectedThemeId === themeInfo.id}
              isCurrentApplied={currentAppliedThemeId === themeInfo.id}
              onSelect={() => onThemeSelect(themeInfo.id)}
              onPreview={() => onThemePreview(themeInfo, device)}
            />
          </Grid>
        ))}
      </Grid>
    </Box>
  );
};

// 메인 컴포넌트
const UIThemeSettingsTab: React.FC = () => {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const { isAuthenticated, user } = useAuth();
  const {
    themeSettings,
    currentDevice,
    currentThemeId,
    previewThemeForDevice,
    applyTheme,
    cancelPreview,
    isPreviewing,
    previewSettings,
    getAvailableThemes,
    getThemeInfo,
    currentUserId,
  } = useUITheme();

  const [previewModalOpen, setPreviewModalOpen] = useState(false);
  const [previewModalTheme, setPreviewModalTheme] = useState<UIThemeInfo | null>(null);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');

  const devices: DeviceType[] = ['pc', 'tablet', 'mobile'];

  // 원본 설정 (적용 버튼 전의 저장된 설정)
  const getOriginalSettings = () => {
    if (isPreviewing && previewSettings) {
      // 미리보기 중이면 previewSettings에서 현재 미리보기 중인 값을 가져옴
      // themeSettings는 이미 effectiveSettings이므로 원본을 따로 가져와야 함
    }
    return themeSettings;
  };

  const handleThemeSelect = (device: DeviceType, themeId: UIThemeId) => {
    console.log('🎨 테마 선택:', { device, themeId, currentDevice, currentThemeId });
    previewThemeForDevice(device, themeId);
  };

  const handleThemePreview = (themeInfo: UIThemeInfo, device: DeviceType) => {
    setPreviewModalTheme(themeInfo);
    setPreviewModalOpen(true);
    // 현재 미리보기 중인 디바이스 저장
    setPreviewDevice(device);
  };
  
  const [previewDevice, setPreviewDevice] = useState<DeviceType>('pc');

  const handleApply = () => {
    applyTheme();
    setSnackbarMessage('테마 설정이 저장되었습니다.');
    setSnackbarOpen(true);
  };

  const handleCancel = () => {
    cancelPreview();
    setSnackbarMessage('변경 사항이 취소되었습니다.');
    setSnackbarOpen(true);
  };

  // 현재 저장된 설정과 미리보기 설정 비교
  const hasChanges = isPreviewing;

  return (
    <Box>
      {/* 사용자 상태 표시 */}
      <Box sx={{ 
        mb: 3, 
        p: 2, 
        borderRadius: 2,
        bgcolor: isDark ? 'rgba(139, 92, 246, 0.1)' : 'rgba(139, 92, 246, 0.05)',
        border: `1px solid ${isDark ? 'rgba(139, 92, 246, 0.3)' : 'rgba(139, 92, 246, 0.2)'}`,
        display: 'flex',
        alignItems: 'center',
        gap: 2,
      }}>
        {isAuthenticated ? (
          <>
            <PersonIcon sx={{ color: 'success.main' }} />
            <Box>
              <Typography variant="subtitle2" fontWeight={600}>
                {user?.name || user?.username} 님의 테마 설정
              </Typography>
              <Typography variant="caption" color="text.secondary">
                로그인 상태 - 테마 설정이 계정에 저장됩니다
              </Typography>
            </Box>
          </>
        ) : (
          <>
            <PersonOutlineIcon sx={{ color: 'warning.main' }} />
            <Box>
              <Typography variant="subtitle2" fontWeight={600}>
                게스트 테마 설정
              </Typography>
              <Typography variant="caption" color="text.secondary">
                비로그인 상태 - 테마 설정이 이 브라우저에만 저장됩니다
              </Typography>
            </Box>
          </>
        )}
      </Box>

      {/* 현재 적용 상태 표시 */}
      <Box sx={{ 
        mb: 3, 
        p: 2.5, 
        borderRadius: 2,
        bgcolor: isDark ? 'rgba(100, 149, 237, 0.1)' : 'rgba(100, 149, 237, 0.05)',
        border: `1px solid ${isDark ? 'rgba(100, 149, 237, 0.3)' : 'rgba(100, 149, 237, 0.2)'}`,
      }}>
        <Typography variant="subtitle2" color="text.secondary" gutterBottom>
          현재 적용 중인 테마
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            {getDeviceIcon(currentDevice)}
            <Typography variant="body1" fontWeight={500}>
              {getDeviceName(currentDevice)}
            </Typography>
          </Box>
          <Typography color="text.secondary">→</Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Chip 
              label={getThemeInfo(currentThemeId)?.badgeCode || 'Default'} 
              size="small"
              color="primary"
            />
            <Typography variant="body1" fontWeight={600} color="primary.main">
              {getThemeInfo(currentThemeId)?.name || '기본'}
            </Typography>
          </Box>
        </Box>
      </Box>

      {/* 변경사항 알림 및 적용 버튼 */}
      {hasChanges && (
        <Alert 
          severity="info" 
          sx={{ mb: 3 }}
          action={
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button 
                size="small" 
                startIcon={<UndoIcon />}
                onClick={handleCancel}
                color="inherit"
              >
                취소
              </Button>
              <Button 
                size="small" 
                variant="contained"
                startIcon={<SaveIcon />}
                onClick={handleApply}
              >
                적용
              </Button>
            </Box>
          }
        >
          테마 설정이 변경되었습니다. 적용 버튼을 눌러 저장하세요.
        </Alert>
      )}

      <Divider sx={{ mb: 3 }} />

      {/* 디바이스별 테마 설정 */}
      <Typography variant="h6" gutterBottom sx={{ mb: 3, display: 'flex', alignItems: 'center', gap: 1 }}>
        📱 디바이스별 UI 테마 선택
      </Typography>

      {devices.map((device) => {
        // 현재 저장된 설정 (previewSettings가 없으면 themeSettings)
        const savedThemeId = isPreviewing 
          ? (previewSettings?.[device] || themeSettings[device])
          : themeSettings[device];
        
        // 원본 저장된 설정 (비교용)
        const originalThemeId = themeSettings[device];

        return (
          <DeviceThemeSection
            key={device}
            device={device}
            selectedThemeId={savedThemeId}
            currentAppliedThemeId={originalThemeId}
            availableThemes={getAvailableThemes(device)}
            onThemeSelect={(themeId) => handleThemeSelect(device, themeId)}
            onThemePreview={(theme, dev) => handleThemePreview(theme, dev)}
          />
        );
      })}

      {/* 안내 메시지 */}
      <Box sx={{ 
        mt: 2, 
        p: 2, 
        borderRadius: 1,
        bgcolor: isDark ? 'rgba(255, 193, 7, 0.1)' : 'rgba(255, 193, 7, 0.05)',
        border: `1px solid ${isDark ? 'rgba(255, 193, 7, 0.3)' : 'rgba(255, 193, 7, 0.2)'}`,
      }}>
        <Typography variant="body2" color="text.secondary">
          💡 <strong>사용 방법:</strong>
          <br />
          1. 원하는 테마의 👁️ 버튼을 클릭하여 전체 화면 미리보기를 확인하세요
          <br />
          2. 테마 카드를 클릭하여 선택하면 미리보기 상태가 됩니다
          <br />
          3. 상단의 "적용" 버튼을 클릭하면 선택한 테마가 저장됩니다
          <br />
          4. 화면 크기에 따라 자동으로 해당 디바이스의 테마가 적용됩니다
        </Typography>
      </Box>

      {/* 미리보기 모달 */}
      <ThemePreviewModal
        open={previewModalOpen}
        onClose={() => setPreviewModalOpen(false)}
        theme={previewModalTheme}
        onApply={() => {
          if (previewModalTheme) {
            handleThemeSelect(previewDevice, previewModalTheme.id);
            setSnackbarMessage(`${previewModalTheme.name} 테마가 선택되었습니다. 적용 버튼을 눌러 저장하세요.`);
            setSnackbarOpen(true);
          }
        }}
        isApplied={previewModalTheme?.id === themeSettings[previewDevice]}
      />

      {/* 스낵바 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={() => setSnackbarOpen(false)}
        message={snackbarMessage}
      />
    </Box>
  );
};

export default UIThemeSettingsTab;
