import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  IconButton,
  CircularProgress,
  Alert,
  Avatar
} from '@mui/material';
import { CloudUpload, Delete, Close } from '@mui/icons-material';
import { useAuthStore } from '../store/authStore';
import Logo from './Logo';

function ChannelLogoManager({ open, onClose, channel, onLogoUpdated }) {
  const { token } = useAuthStore();
  const [uploading, setUploading] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState('');
  const [preview, setPreview] = useState(null);

  const handleFileSelect = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    // Validate file size (5MB max)
    if (file.size > 5 * 1024 * 1024) {
      setError('File size must be less than 5MB');
      return;
    }

    // Validate file type
    if (!file.type.match(/image\/(jpeg|jpg|png|gif|svg\+xml|webp)/)) {
      setError('Only image files are allowed (JPG, PNG, GIF, SVG, WebP)');
      return;
    }

    setError('');
    setUploading(true);

    // Create preview
    const reader = new FileReader();
    reader.onload = (e) => setPreview(e.target.result);
    reader.readAsDataURL(file);

    // Upload to server
    const formData = new FormData();
    formData.append('logo', file);

    try {
      const response = await fetch(`/api/channels/${channel.id}/logo`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`
        },
        body: formData
      });

      if (response.ok) {
        const data = await response.json();
        onLogoUpdated({ ...channel, logo: data.logoUrl });
        setTimeout(() => {
          onClose();
          setPreview(null);
        }, 1000);
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Failed to upload logo');
      }
    } catch (err) {
      setError('Network error. Please try again.');
    } finally {
      setUploading(false);
    }
  };

  const handleDeleteLogo = async () => {
    setDeleting(true);
    setError('');

    try {
      const response = await fetch(`/api/channels/${channel.id}/logo`, {
        method: 'DELETE',
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      if (response.ok) {
        onLogoUpdated({ ...channel, logo: null });
        onClose();
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Failed to delete logo');
      }
    } catch (err) {
      setError('Network error. Please try again.');
    } finally {
      setDeleting(false);
    }
  };

  const currentLogo = preview || channel?.logo;
  const hasCustomLogo = channel?.custom_logo || preview;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant="h6">Manage Channel Logo</Typography>
          <IconButton size="small" onClick={onClose}>
            <Close />
          </IconButton>
        </Box>
      </DialogTitle>
      
      <DialogContent>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError('')}>
            {error}
          </Alert>
        )}

        <Box sx={{ textAlign: 'center', mb: 3 }}>
          <Typography variant="body2" color="text.secondary" gutterBottom>
            {channel?.name}
          </Typography>
        </Box>

        {/* Current Logo Preview */}
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: 200,
            bgcolor: 'background.default',
            borderRadius: 2,
            mb: 3,
            position: 'relative',
            border: '2px dashed',
            borderColor: 'divider'
          }}
        >
          {uploading ? (
            <CircularProgress />
          ) : currentLogo ? (
            <img
              src={currentLogo}
              alt={channel?.name}
              style={{
                maxWidth: '100%',
                maxHeight: '100%',
                objectFit: 'contain'
              }}
              onError={(e) => {
                e.target.style.display = 'none';
                e.target.nextSibling.style.display = 'flex';
              }}
            />
          ) : null}
          
          {!currentLogo && !uploading && (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}>
              <Logo size={80} />
              <Typography variant="caption" color="text.secondary">
                No logo uploaded
              </Typography>
            </Box>
          )}
        </Box>

        {/* Upload Instructions */}
        <Typography variant="caption" color="text.secondary" display="block" sx={{ mb: 2 }}>
          • Supported formats: JPG, PNG, GIF, SVG, WebP<br />
          • Maximum size: 5MB<br />
          • Recommended: Square images (1:1 ratio)
        </Typography>

        {/* Actions */}
        <Box sx={{ display: 'flex', gap: 1, flexDirection: 'column' }}>
          <Button
            variant="contained"
            component="label"
            startIcon={<CloudUpload />}
            disabled={uploading || deleting}
            fullWidth
          >
            {hasCustomLogo ? 'Replace Logo' : 'Upload Logo'}
            <input
              type="file"
              hidden
              accept="image/jpeg,image/jpg,image/png,image/gif,image/svg+xml,image/webp"
              onChange={handleFileSelect}
            />
          </Button>

          {hasCustomLogo && (
            <Button
              variant="outlined"
              color="error"
              startIcon={deleting ? <CircularProgress size={20} /> : <Delete />}
              onClick={handleDeleteLogo}
              disabled={uploading || deleting}
              fullWidth
            >
              Delete Custom Logo
            </Button>
          )}
        </Box>

        {hasCustomLogo && (
          <Typography variant="caption" color="text.secondary" sx={{ mt: 2, display: 'block', textAlign: 'center' }}>
            Custom logo will be used instead of the official channel logo
          </Typography>
        )}
      </DialogContent>

      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={onClose} disabled={uploading || deleting}>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default ChannelLogoManager;
