import { useState, useCallback, useRef } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  TextField,
  Tabs,
  Tab,
  CircularProgress,
  Alert,
  IconButton,
  useMediaQuery,
  useTheme,
  AppBar,
  Toolbar,
} from "@mui/material";
import {
  CloudUpload as UploadIcon,
  Link as LinkIcon,
  Close as CloseIcon,
  Image as ImageIcon,
  ArrowBack as ArrowBackIcon,
} from "@mui/icons-material";

interface ImageUploadDialogProps {
  open: boolean;
  onClose: () => void;
  onImageSelected: (imageData: ImageData) => void;
}

export interface ImageData {
  src: string; // Base64 data URI
  originalWidth: number;
  originalHeight: number;
  fileName?: string;
  mimeType: string;
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel({ children, value, index }: TabPanelProps) {
  return (
    <div role="tabpanel" hidden={value !== index}>
      {value === index && <Box sx={{ pt: 2 }}>{children}</Box>}
    </div>
  );
}

export default function ImageUploadDialog({
  open,
  onClose,
  onImageSelected,
}: ImageUploadDialogProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [tab, setTab] = useState(0);
  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [preview, setPreview] = useState<ImageData | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);

  const resetState = useCallback(() => {
    setUrl("");
    setLoading(false);
    setError(null);
    setPreview(null);
    setIsDragging(false);
  }, []);

  const handleClose = useCallback(() => {
    resetState();
    onClose();
  }, [onClose, resetState]);

  const processFile = useCallback((file: File): Promise<ImageData> => {
    return new Promise((resolve, reject) => {
      // Validate file type
      if (!file.type.startsWith("image/")) {
        reject(new Error("Il file selezionato non è un'immagine valida"));
        return;
      }

      // Validate file size (max 10MB)
      if (file.size > 10 * 1024 * 1024) {
        reject(new Error("L'immagine è troppo grande (max 10MB)"));
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const dataUrl = e.target?.result as string;

        // Create image to get dimensions
        const img = new Image();
        img.onload = () => {
          resolve({
            src: dataUrl,
            originalWidth: img.naturalWidth,
            originalHeight: img.naturalHeight,
            fileName: file.name,
            mimeType: file.type,
          });
        };
        img.onerror = () => {
          reject(new Error("Impossibile caricare l'immagine"));
        };
        img.src = dataUrl;
      };
      reader.onerror = () => {
        reject(new Error("Errore nella lettura del file"));
      };
      reader.readAsDataURL(file);
    });
  }, []);

  const handleFileSelect = useCallback(
    async (files: FileList | null) => {
      if (!files || files.length === 0) return;

      setLoading(true);
      setError(null);

      try {
        const imageData = await processFile(files[0]);
        setPreview(imageData);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Errore sconosciuto");
      } finally {
        setLoading(false);
      }
    },
    [processFile],
  );

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);
      handleFileSelect(e.dataTransfer.files);
    },
    [handleFileSelect],
  );

  const handleUrlLoad = useCallback(async () => {
    if (!url.trim()) {
      setError("Inserisci un URL valido");
      return;
    }

    setLoading(true);
    setError(null);

    try {
      // Fetch image from URL
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error("Impossibile scaricare l'immagine dall'URL");
      }

      const contentType = response.headers.get("content-type");
      if (!contentType?.startsWith("image/")) {
        throw new Error("L'URL non punta a un'immagine valida");
      }

      const blob = await response.blob();
      const file = new File([blob], "image", { type: contentType });
      const imageData = await processFile(file);
      setPreview(imageData);
    } catch (err) {
      // If direct fetch fails (CORS), try loading the image directly
      try {
        const img = new Image();
        img.crossOrigin = "anonymous";

        await new Promise<void>((resolve, reject) => {
          img.onload = async () => {
            // Create canvas to convert to base64
            const canvas = document.createElement("canvas");
            canvas.width = img.naturalWidth;
            canvas.height = img.naturalHeight;
            const ctx = canvas.getContext("2d");
            if (!ctx) {
              reject(new Error("Impossibile creare il contesto canvas"));
              return;
            }
            ctx.drawImage(img, 0, 0);

            try {
              const dataUrl = canvas.toDataURL("image/png");
              setPreview({
                src: dataUrl,
                originalWidth: img.naturalWidth,
                originalHeight: img.naturalHeight,
                mimeType: "image/png",
              });
              resolve();
            } catch {
              reject(new Error("Impossibile convertire l'immagine (CORS)"));
            }
          };
          img.onerror = () => {
            reject(new Error("Impossibile caricare l'immagine dall'URL"));
          };
          img.src = url;
        });
      } catch (innerErr) {
        setError(
          innerErr instanceof Error
            ? innerErr.message
            : "Errore nel caricamento dell'immagine",
        );
      }
    } finally {
      setLoading(false);
    }
  }, [url, processFile]);

  const handleConfirm = useCallback(() => {
    if (preview) {
      onImageSelected(preview);
      handleClose();
    }
  }, [preview, onImageSelected, handleClose]);

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      fullScreen={isMobile}
    >
      {isMobile ? (
        // Mobile: AppBar header
        <AppBar position="static" color="default" elevation={0}>
          <Toolbar>
            <IconButton edge="start" onClick={handleClose} sx={{ mr: 1 }}>
              <ArrowBackIcon />
            </IconButton>
            <ImageIcon color="primary" sx={{ mr: 1 }} />
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              Inserisci Immagine
            </Typography>
          </Toolbar>
        </AppBar>
      ) : (
        // Desktop: Standard DialogTitle
        <DialogTitle>
          <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
          >
            <Box display="flex" alignItems="center" gap={1}>
              <ImageIcon color="primary" />
              <Typography variant="h6">Inserisci Immagine</Typography>
            </Box>
            <IconButton size="small" onClick={handleClose}>
              <CloseIcon />
            </IconButton>
          </Box>
        </DialogTitle>
      )}

      <DialogContent sx={{ p: isMobile ? 2 : 3 }}>
        <Tabs
          value={tab}
          onChange={(_, v) => {
            setTab(v);
            setError(null);
            setPreview(null);
          }}
          sx={{ borderBottom: 1, borderColor: "divider" }}
          variant={isMobile ? "fullWidth" : "standard"}
        >
          <Tab
            icon={<UploadIcon />}
            label={isMobile ? "Carica" : "Carica File"}
            iconPosition="start"
            sx={{ minHeight: isMobile ? 56 : 48 }}
          />
          <Tab
            icon={<LinkIcon />}
            label={isMobile ? "URL" : "Da URL"}
            iconPosition="start"
            sx={{ minHeight: isMobile ? 56 : 48 }}
          />
        </Tabs>

        {error && (
          <Alert severity="error" sx={{ mt: 2 }} onClose={() => setError(null)}>
            {error}
          </Alert>
        )}

        <TabPanel value={tab} index={0}>
          {/* File Upload */}
          <Box
            sx={{
              border: 2,
              borderStyle: "dashed",
              borderColor: isDragging ? "primary.main" : "divider",
              borderRadius: 2,
              p: isMobile ? 3 : 4,
              textAlign: "center",
              bgcolor: isDragging ? "primary.50" : "grey.50",
              cursor: "pointer",
              transition: "all 0.2s",
              minHeight: isMobile ? 150 : "auto",
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              "&:hover": {
                borderColor: "primary.light",
                bgcolor: "primary.50",
              },
            }}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              hidden
              onChange={(e) => handleFileSelect(e.target.files)}
            />
            {loading ? (
              <CircularProgress />
            ) : (
              <>
                <UploadIcon
                  sx={{
                    fontSize: isMobile ? 40 : 48,
                    color: "text.secondary",
                    mb: 1,
                  }}
                />
                <Typography variant="body1" gutterBottom>
                  {isMobile
                    ? "Tocca per selezionare"
                    : "Trascina un'immagine qui"}
                </Typography>
                {!isMobile && (
                  <Typography variant="body2" color="text.secondary">
                    oppure clicca per selezionare un file
                  </Typography>
                )}
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ mt: 1 }}
                >
                  {isMobile
                    ? "JPG, PNG, GIF, WebP (max 10MB)"
                    : "Formati supportati: JPG, PNG, GIF, WebP, SVG (max 10MB)"}
                </Typography>
              </>
            )}
          </Box>
        </TabPanel>

        <TabPanel value={tab} index={1}>
          {/* URL Input */}
          <Box display="flex" flexDirection="column" gap={2}>
            <TextField
              label="URL Immagine"
              placeholder="https://esempio.com/immagine.jpg"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              fullWidth
              disabled={loading}
              size={isMobile ? "medium" : "small"}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  handleUrlLoad();
                }
              }}
            />
            <Button
              variant="outlined"
              onClick={handleUrlLoad}
              disabled={loading || !url.trim()}
              startIcon={
                loading ? <CircularProgress size={20} /> : <LinkIcon />
              }
              size={isMobile ? "large" : "medium"}
              fullWidth={isMobile}
            >
              {loading ? "Caricamento..." : "Carica da URL"}
            </Button>
          </Box>
        </TabPanel>

        {/* Preview */}
        {preview && (
          <Box
            sx={{
              mt: 3,
              p: 2,
              border: 1,
              borderColor: "divider",
              borderRadius: 2,
              bgcolor: "grey.50",
            }}
          >
            <Typography variant="subtitle2" color="primary" gutterBottom>
              Anteprima
            </Typography>
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                bgcolor: "white",
                borderRadius: 1,
                p: 1,
                mb: 1,
              }}
            >
              <img
                src={preview.src}
                alt="Preview"
                style={{
                  maxWidth: "100%",
                  maxHeight: isMobile ? 150 : 200,
                  objectFit: "contain",
                }}
              />
            </Box>
            <Box
              display="flex"
              flexDirection={isMobile ? "column" : "row"}
              justifyContent="space-between"
              alignItems={isMobile ? "flex-start" : "center"}
              gap={isMobile ? 0.5 : 0}
            >
              <Typography variant="caption" color="text.secondary">
                {preview.originalWidth} × {preview.originalHeight} px
              </Typography>
              {preview.fileName && (
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{
                    maxWidth: isMobile ? "100%" : 200,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {preview.fileName}
                </Typography>
              )}
            </Box>
          </Box>
        )}
      </DialogContent>

      <DialogActions
        sx={{
          px: isMobile ? 2 : 3,
          pb: isMobile ? 3 : 2,
          pt: isMobile ? 1 : 0,
          flexDirection: isMobile ? "column" : "row",
          gap: isMobile ? 1 : 0,
        }}
      >
        {isMobile ? (
          // Mobile: Stacked full-width buttons
          <>
            <Button
              variant="contained"
              onClick={handleConfirm}
              disabled={!preview}
              startIcon={<ImageIcon />}
              fullWidth
              size="large"
            >
              Inserisci Immagine
            </Button>
            <Button onClick={handleClose} fullWidth>
              Annulla
            </Button>
          </>
        ) : (
          // Desktop: Standard layout
          <>
            <Button onClick={handleClose}>Annulla</Button>
            <Button
              variant="contained"
              onClick={handleConfirm}
              disabled={!preview}
              startIcon={<ImageIcon />}
            >
              Inserisci Immagine
            </Button>
          </>
        )}
      </DialogActions>
    </Dialog>
  );
}
