import CheckIcon from "@mui/icons-material/Check";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, Typography, IconButton, Tooltip, Divider } from "@mui/material";
import { useState } from "react";

import { useTransformVersions } from "./hooks/useTransformVersions";
import TransformEditHistoryPanel from "./TransformEditHistoryPanel";
import { TraceTransform } from "./types";

interface TransformDetailsModalProps {
  open: boolean;
  onClose: () => void;
  transform: TraceTransform | null;
}

export const TransformDetailsModal: React.FC<TransformDetailsModalProps> = ({ open, onClose, transform }) => {
  const [copied, setCopied] = useState(false);
  const { data: versions = [] } = useTransformVersions(transform?.id);
  const definition = versions[0]?.definition;

  if (!transform) return null;

  const handleCopyId = async () => {
    try {
      await navigator.clipboard.writeText(transform.id);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy transform ID:", err);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>Transform Details: {transform.name}</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 1 }}>
          {/* Transform ID Section */}
          <Box sx={{ mb: 3 }}>
            <Typography variant="subtitle2" fontWeight="medium" gutterBottom>
              Transform ID
            </Typography>
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1,
                p: 1.5,
                backgroundColor: "action.hover",
                borderRadius: 1,
                border: "1px solid",
                borderColor: "divider",
              }}
            >
              <Typography
                variant="body2"
                sx={{
                  fontFamily: "monospace",
                  fontSize: 13,
                  flex: 1,
                  wordBreak: "break-all",
                }}
              >
                {transform.id}
              </Typography>
              <Tooltip title={copied ? "Copied!" : "Copy ID"}>
                <IconButton
                  size="small"
                  onClick={handleCopyId}
                  sx={{
                    color: copied ? "success.main" : "text.secondary",
                  }}
                >
                  {copied ? <CheckIcon fontSize="small" /> : <ContentCopyIcon fontSize="small" />}
                </IconButton>
              </Tooltip>
            </Box>
          </Box>

          {transform.description && (
            <Box sx={{ mb: 3 }}>
              <Typography variant="subtitle2" fontWeight="medium" gutterBottom>
                Description
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {transform.description}
              </Typography>
            </Box>
          )}

          <Box sx={{ mb: 3 }}>
            <Typography variant="subtitle2" fontWeight="medium" gutterBottom>
              Variable Mappings ({definition?.variables.length ?? 0})
            </Typography>
            <Box sx={{ display: "flex", flexDirection: "column", gap: 1, mt: 1 }}>
              {(definition?.variables ?? []).map((variable, idx) => (
                <Box
                  key={idx}
                  sx={{
                    p: 2,
                    backgroundColor: "action.hover",
                    borderRadius: 1,
                    border: "1px solid",
                    borderColor: "divider",
                  }}
                >
                  <Typography variant="body2" fontWeight="medium">
                    {variable.variable_name}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Span: <code>{variable.span_name}</code> → Path: <code>{variable.attribute_path}</code>
                  </Typography>
                  {variable.fallback !== undefined && (
                    <Typography variant="caption" color="text.secondary" display="block">
                      Fallback: {JSON.stringify(variable.fallback)}
                    </Typography>
                  )}
                </Box>
              ))}
            </Box>
          </Box>

          <Box>
            <Typography variant="subtitle2" fontWeight="medium" gutterBottom>
              Full JSON Definition
            </Typography>
            <Box
              component="pre"
              sx={{
                backgroundColor: "background.paper",
                p: 2,
                borderRadius: 1,
                overflow: "auto",
                maxHeight: 400,
                fontSize: 12,
                border: 1,
                borderColor: "divider",
                m: 0,
              }}
            >
              {JSON.stringify(definition, null, 2)}
            </Box>
          </Box>

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

          <Box>
            <Typography variant="subtitle2" fontWeight="medium" gutterBottom>
              Edit History
            </Typography>
            <TransformEditHistoryPanel transformId={transform.id} />
          </Box>
        </Box>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={onClose} variant="outlined">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default TransformDetailsModal;
