import React, { useState } from "react";
import {
  Typography,
  TextField,
  Button,
  Box,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Divider,
  IconButton,
  Snackbar,
} from "@mui/material";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import CloseIcon from "@mui/icons-material/Close";
import { useQuery, useMutation } from "@apollo/client";
import { CREATE_ASSET } from "../../graphql/mutation";
import Alert from "@mui/material/Alert";
import { useNavigate } from "react-router-dom";
import imageCompression from "browser-image-compression";
import { useTheme } from "@mui/material/styles";
import { EDIT_PROFILE_TEXT, ERROR_MESSAGES, TYPOGRAPHY_TEXT } from "../../const";

interface IProduct {
  id: number;
  productName: string;
  productImage: string | null; 
  description: string;
  assetClass: string;
  minInvestment: string;
  investorType: string;
}

interface IAsset {
  assetName: string;
  benchmark: string;
  inceptionDate: string;
  products: IProduct[];
}

const AddAsset: React.FC = () => {
  const [createAsset] = useMutation(CREATE_ASSET);
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = theme.breakpoints.down("sm");
  const isTablet = theme.breakpoints.between("sm", "md");
  const [assetData, setAssetData] = useState<IAsset>({
    assetName: "",
    benchmark: "",
    inceptionDate: "",
    products: [
      {
        id: 1,
        productName: "",
        productImage: null,
        description: "",
        assetClass: "",
        minInvestment: "",
        investorType: "",
      },
    ],
  });

  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">("success");

  const handleAssetChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setAssetData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleProductChange = (
    index: number,
    e: React.ChangeEvent<HTMLInputElement | { name?: string; value: unknown }>
  ) => {
    const { name, value } = e.target;
    const updatedProducts = [...assetData.products];
    updatedProducts[index] = {
      ...updatedProducts[index],
      [name as string]: value,
    };
    setAssetData((prev) => ({ ...prev, products: updatedProducts }));
  };

  const handleProductFileChange = async (
    index: number,
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      const supportedTypes = ["image/jpeg", "image/jpg", "image/png"];
      if (!supportedTypes.includes(file.type)) {
        console.error(ERROR_MESSAGES.INVALID_FILE_TYPE, file.type, file.name);
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        console.error(ERROR_MESSAGES.FILE_TOO_LARGE, file.size, file.name);
        return;
      }

      try {
        const options = {
          maxSizeMB: 0.5,
          maxWidthOrHeight: isMobile ? 600 : isTablet ? 800 : 1000,
          useWebWorker: true,
          initialQuality: 0.8,
        };

        const compressedFile = await imageCompression(file, options);
        const reader = new FileReader();
        reader.onloadend = () => {
          const base64String = reader.result as string;
          const updatedProducts = [...assetData.products];
          updatedProducts[index].productImage = base64String;
          setAssetData((prev) => ({ ...prev, products: updatedProducts }));
        };
        reader.readAsDataURL(compressedFile);
      } catch (error) {
        console.error(ERROR_MESSAGES.ERROR_COMPRESSING_IMAGE, error, file.name);
      }
    }
  };

  const addProduct = () => {
    const newProduct: IProduct = {
      id: Date.now(),
      productName: "",
      productImage: null,
      description: "",
      assetClass: "",
      minInvestment: "",
      investorType: "",
    };
    setAssetData((prev) => ({
      ...prev,
      products: [...prev.products, newProduct],
    }));
  };

  const removeProduct = (id: number) => {
    setAssetData((prev) => ({
      ...prev,
      products: prev.products.filter((product) => product.id !== id),
    }));
  };

  const handleSnackbarClose = (event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === "clickaway") return;
    setSnackbarOpen(false);
    navigate("/admin/assets");
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const input = {
      market: assetData.assetName,
      benchmark: assetData.benchmark,
      inceptionDate: assetData.inceptionDate,
      numberOfInvestments: assetData.products.length,
      products: assetData.products.map((product) => ({
        productName: product.productName,
        productImage: product.productImage,
        description: product.description,
        assetClass: product.assetClass,
        minimumInvestment: parseFloat(product.minInvestment),
        investorType: product.investorType,
      })),
    };

    try {
      const { data } = await createAsset({
        variables: { input },
      });
      if (data?.createAsset?.success) {
        setSnackbarMessage(ERROR_MESSAGES.ASSET_CREATED_SUCCESSFULLY);
        setSnackbarSeverity("success");
        setSnackbarOpen(true);
      } else {
        setSnackbarMessage(data?.createAsset?.message || ERROR_MESSAGES.FAILED_TO_CREATE_ASSET);
        setSnackbarSeverity("error");
        setSnackbarOpen(true);
        console.error("Error:", data?.createAsset?.message);
      }
    } catch (error) {
      setSnackbarMessage(ERROR_MESSAGES.FAILED_TO_CREATE_ASSET);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      console.error(ERROR_MESSAGES.FAILED_TO_CREATE_ASSET, error);
    }
  };

  return (
    <Box sx={{ p: 3, width: "100%", boxSizing: "border-box" }}>
      <Typography
        variant="h5"
        component="h1"
        sx={{ fontWeight: 600, color: "#222222", mb: 3 }}
      >
       {TYPOGRAPHY_TEXT.ADD_ASSET}
      </Typography>

      <form onSubmit={handleSubmit}>
        <Box
          sx={{
            p: { xs: 2, md: 3 },
            bgcolor: "#FFFFFF",
            border: "1px solid #E0E0E0",
            borderRadius: 2,
          }}
        >
          <Typography variant="h6" sx={{ mb: 3, color: "#021935" }}>
            {TYPOGRAPHY_TEXT.ASSET_DETAILS}
          </Typography>
          <Box
            sx={{
              display: "flex",
              flexDirection: { xs: "column", md: "row" },
              gap: 3,
            }}
          >
            <TextField
              fullWidth
              required
              name="assetName"
              label="Asset Name (Market)"
              value={assetData.assetName}
              onChange={handleAssetChange}
            />
            <TextField
              fullWidth
              name="benchmark"
              label="Benchmark"
              value={assetData.benchmark}
              onChange={handleAssetChange}
            />
            <TextField
              fullWidth
              required
              name="inceptionDate"
              label="Inception Date"
              type="date"
              value={assetData.inceptionDate}
              onChange={handleAssetChange}
              InputLabelProps={{ shrink: true }}
            />
          </Box>
        </Box>

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

        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              mb: 3,
            }}
          >
            <Box>
              <Typography variant="h6" sx={{ color: "#021935" }}>
                {TYPOGRAPHY_TEXT.PRODUCTS}
              </Typography>
              <Typography variant="body2" color="textSecondary">
                {TYPOGRAPHY_TEXT.NUMBER_OF_INVESTMENTS}{assetData.products.length}
              </Typography>
            </Box>
            <Button
              variant="outlined"
              startIcon={<AddCircleOutlineIcon />}
              onClick={addProduct}
            >
             {TYPOGRAPHY_TEXT.ADD_PRODUCT}
            </Button>
          </Box>

          <Box sx={{ display: "flex", flexDirection: "column", gap: 3 }}>
            {assetData.products.map((product, index) => (
              <Box
                key={product.id}
                sx={{
                  p: 3,
                  bgcolor: "#FFFFFF",
                  border: "1px solid #E0E0E0",
                  borderRadius: 2,
                  position: "relative",
                }}
              >
                <IconButton
                  onClick={() => removeProduct(product.id)}
                  sx={{ position: "absolute", top: 8, right: 8 }}
                >
                  <CloseIcon />
                </IconButton>

                <Box
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                    gap: 3,
                    mt: 2,
                  }}
                >
                  <TextField
                    fullWidth
                    required
                    name="productName"
                    label="Product Name"
                    value={product.productName}
                    onChange={(e) => handleProductChange(index, e)}
                  />
                  <TextField
                    fullWidth
                    required
                    multiline
                    rows={3}
                    name="description"
                    label="Description"
                    value={product.description}
                    onChange={(e) => handleProductChange(index, e)}
                  />

                  <Box
                    sx={{
                      display: "flex",
                      flexDirection: { xs: "column", sm: "row" },
                      gap: 3,
                    }}
                  >
                    <FormControl fullWidth required>
                      <InputLabel>Asset Class</InputLabel>
                      <Select
                        name="assetClass"
                        value={product.assetClass}
                        label="Asset Class"
                        onChange={(e) =>
                          handleProductChange(
                            index,
                            e as React.ChangeEvent<{
                              name?: string;
                              value: unknown;
                            }>
                          )
                        }
                      >
                        <MenuItem value="Equity">Equity</MenuItem>
                        <MenuItem value="Fixed Income">Fixed Income</MenuItem>
                        <MenuItem value="Real Estate">Real Estate</MenuItem>
                        <MenuItem value="Commodities">Commodities</MenuItem>
                      </Select>
                    </FormControl>
                    <FormControl fullWidth required>
                      <InputLabel>Investor Type</InputLabel>
                      <Select
                        name="investorType"
                        value={product.investorType}
                        label="Investor Type"
                        onChange={(e) =>
                          handleProductChange(
                            index,
                            e as React.ChangeEvent<{
                              name?: string;
                              value: unknown;
                            }>
                          )
                        }
                      >
                        <MenuItem value="Retail">Retail</MenuItem>
                        <MenuItem value="Institutional">Institutional</MenuItem>
                        <MenuItem value="Accredited">Accredited</MenuItem>
                      </Select>
                    </FormControl>
                  </Box>

                  <Box
                    sx={{
                      display: "flex",
                      flexDirection: { xs: "column", sm: "row" },
                      gap: 3,
                    }}
                  >
                    <TextField
                      fullWidth
                      required
                      name="minInvestment"
                      label="Minimum Investment ($)"
                      type="number"
                      value={product.minInvestment}
                      onChange={(e) => handleProductChange(index, e)}
                    />
                    <Button
                      component="label"
                      variant="outlined"
                      sx={{ width: { xs: "100%", sm: "auto" }, flexShrink: 0 }}
                    >
                      Upload Product Image
                      <input
                        type="file"
                        hidden
                        accept="image/*"
                        onChange={(e) => handleProductFileChange(index, e)}
                      />
                    </Button>
                    {product.productImage && (
                      <Typography variant="body2" sx={{ alignSelf: "center" }}>
                        {product.productImage.substring(0, 20)}... {/* Display truncated base64 for preview */}
                      </Typography>
                    )}
                  </Box>
                </Box>
              </Box>
            ))}
          </Box>
        </Box>

        <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 4 }}>
          <Button
            type="submit"
            variant="contained"
            sx={{
              px: 5,
              py: 1.5,
              bgcolor: "#021935",
              "&:hover": { bgcolor: "#1565C0" },
            }}
          >
           {EDIT_PROFILE_TEXT.SAVE_BUTTON}
          </Button>
        </Box>

        <Snackbar
          open={snackbarOpen}
          autoHideDuration={2000}
          onClose={handleSnackbarClose}
          anchorOrigin={{ vertical: "top", horizontal: "center" }}
          sx={{
            "& .MuiSnackbarContent-root": {
              borderRadius: "8px",
              backgroundColor: "#f5f5f5",
            },
          }}
        >
          <Alert
            onClose={handleSnackbarClose}
            severity={snackbarSeverity}
            sx={{
              width: "100%",
              fontSize: "16px",
            }}
            action={
              <IconButton
                size="small"
                aria-label="close"
                color="inherit"
                onClick={handleSnackbarClose}
              >
                <CloseIcon fontSize="small" />
              </IconButton>
            }
          >
            {snackbarMessage}
          </Alert>
        </Snackbar>
      </form>
    </Box>
  );
};

export default AddAsset;