import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Typography,
  useMediaQuery,
  useTheme,
  Card,
  CardContent,
  CardMedia,
  Box,
  CircularProgress,
  Button,
} from "@mui/material";
import { useQuery } from "@apollo/client";
import { GET_ASSET_BY_ID } from "../../graphql/query";
import { ERROR_MESSAGES, TYPOGRAPHY_TEXT } from "../../const";

const CustomerAssetView: React.FC = () => {
  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("md"));
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [asset, setAsset] = useState<any>(null);

  const { loading, error, data } = useQuery(GET_ASSET_BY_ID, {
    variables: { id },
    fetchPolicy: "network-only",
    onCompleted: (data) => {
      setAsset(data.getAssetById);
    },
  });

  const formatDate = (timestamp: string): string => {
    if (!timestamp || isNaN(parseInt(timestamp))) {
      return "Invalid Date";
    }
    const date = new Date(parseInt(timestamp));
    if (!isNaN(date.getTime())) {
      return date.toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });
    }
    return "Invalid Date";
  };

  const handleViewToken = (product: any) => {
    navigate(`/assetsview/product/${product.id}`, { state: { product } });
  };

  if (loading) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "85vh",
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  if (error || !asset) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "85vh",
        }}
      >
        <Typography
          variant="h6"
          sx={{ color: "red", textAlign: "center" }}
        >
          {ERROR_MESSAGES.ERROR_LOADING_ASSET_NOT_FOUND}
        </Typography>
      </Box>
    );
  }

  const demoAsset = {
    market: "IntelliWealth Stablecoin",
    numberOfInvestments: 2,
    benchmark: "swrtrrw",
    inceptionDate: "12/10/2010",
    products: asset.products, 
  };

  return (
    <Box
      sx={{
        padding: "20px",
        minHeight: "85vh",
        bgcolor: "#F9FAFC",
      }}
    >
      <Typography
        variant="h5"
        gutterBottom
        sx={{
          color: "#1A202C",
          fontWeight: 600,
          letterSpacing: "-0.3px",
          padding: "5px",
          textAlign: isSmallScreen ? "center" : "left",
        }}
      >
        {TYPOGRAPHY_TEXT.ASSET_DETAILS}
      </Typography>
      <Box
        sx={{
          display: "flex",
          flexWrap: "wrap",
          gap: "20px",
          mb: 4,
          border: "1px solid #E0E0E0",
          borderRadius: "8px",
          p: 2,
          bgcolor: "#FFF",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.05)",
        }}
      >
        <Box sx={{ flex: "1 1 200px", minWidth: 0 }}>
          <Typography variant="body1" sx={{ fontWeight: 500, color: "#1A202C" }}>
            {TYPOGRAPHY_TEXT.MARKET}:
          </Typography>
          <Typography variant="body1" sx={{ color: "#666" }}>
            {demoAsset.market}
          </Typography>
        </Box>
        <Box sx={{ flex: "1 1 200px", minWidth: 0 }}>
          <Typography variant="body1" sx={{ fontWeight: 500, color: "#1A202C" }}>
            {TYPOGRAPHY_TEXT.NUMBER_OF_INVESTMENT}:
          </Typography>
          <Typography variant="body1" sx={{ color: "#666" }}>
            {demoAsset.numberOfInvestments}
          </Typography>
        </Box>
        <Box sx={{ flex: "1 1 200px", minWidth: 0 }}>
          <Typography variant="body1" sx={{ fontWeight: 500, color: "#1A202C" }}>
            {TYPOGRAPHY_TEXT.Benchmark}:
          </Typography>
          <Typography variant="body1" sx={{ color: "#666" }}>
            {demoAsset.benchmark}
          </Typography>
        </Box>
        <Box sx={{ flex: "1 1 200px", minWidth: 0 }}>
          <Typography variant="body1" sx={{ fontWeight: 500, color: "#1A202C" }}>
            {TYPOGRAPHY_TEXT.InceptionDate}:
          </Typography>
          <Typography variant="body1" sx={{ color: "#666" }}>
            {demoAsset.inceptionDate}
          </Typography>
        </Box>
      </Box>
      <Typography
        variant="h6"
        sx={{
          color: "#1A202C",
          fontWeight: 500,
          marginBottom: "20px",
        }}
      >
        {TYPOGRAPHY_TEXT.PRODUCTS}
      </Typography>
      <Box
        sx={{
          display: "flex",
          flexWrap: "wrap",
          gap: "20px",
          justifyContent: isSmallScreen ? "center" : "flex-start",
        }}
      >
        {demoAsset.products.map((product: any) => (
          <Card
            key={product.id}
            sx={{
              width: isSmallScreen ? "100%" : "300px",
              maxWidth: "400px",
              border: "0.1px solid #f0efefff",
              borderRadius: "8px",
              display: "flex",
              flexDirection: "column",
            }}
          >
            {product.productImage && (
              <CardMedia
                component="img"
                height="140"
                image={product.productImage}
                alt={product.productName}
                sx={{ objectFit: "cover", p: 1, width: "auto" }} 
              />
            )}
            <CardContent sx={{ flexGrow: 1 }}>
              <Typography variant="h6" gutterBottom>
                {product.productName}
              </Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                {product.description}
              </Typography>
              <Typography variant="body2" color="text.primary">
                <strong>{TYPOGRAPHY_TEXT.ASSET_CLASS}:</strong> {product.assetClass}
              </Typography>
              <Typography variant="body2" color="text.primary">
                <strong>{TYPOGRAPHY_TEXT.MINIMUM_INVESTMENT}:</strong> ${product.minimumInvestment.toLocaleString()}
              </Typography>
              <Typography variant="body2" color="text.primary">
                <strong>{TYPOGRAPHY_TEXT.INVESTOR_TYPE}:</strong> {product.investorType}
              </Typography>
              <Button
                variant="contained"
                color="primary"
                onClick={() => handleViewToken(product)}
                sx={{
                  marginTop: "16px",
                  textTransform: "none",
                  fontSize: "14px",
                  borderRadius: "8px",
                }}
              >
                {TYPOGRAPHY_TEXT.VIEW_TOKEN}
              </Button>
            </CardContent>
          </Card>
        ))}
      </Box>
    </Box>
  );
};

export default CustomerAssetView;