import React from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  Grid,
  Button,
  Typography,
  makeStyles,
} from '@material-ui/core';
import BarChartIcon from '@material-ui/icons/BarChart';
import ListIcon from '@material-ui/icons/List';
import ShowChartIcon from '@material-ui/icons/ShowChart';
import { useApi, identityApiRef } from '@backstage/core-plugin-api';
import { MomText } from '@container-mom/theme';

const useStyles = makeStyles(theme => ({
  card: {
    height: '100%',
  },
  button: {
    width: '100%',
    justifyContent: 'flex-start',
    padding: theme.spacing(2),
    textTransform: 'none',
  },
  icon: {
    marginRight: theme.spacing(1),
  },
  sectionTitle: {
    marginTop: theme.spacing(2),
    marginBottom: theme.spacing(1),
    color: theme.palette.text.secondary,
  },
}));

interface ObservabilityCardProps {
  customerId?: string;
}

export const ObservabilityCard: React.FC<ObservabilityCardProps> = ({ 
  customerId: propCustomerId 
}) => {
  const classes = useStyles();
  const identityApi = useApi(identityApiRef);
  const [userIdentity, setUserIdentity] = React.useState<{
    customerId?: string;
  }>({});

  React.useEffect(() => {
    identityApi.getBackstageIdentity().then(identity => {
      // Extract customer ID from user entity metadata
      const userRef = identity.userEntityRef;
      // Assuming customer ID is stored in user entity metadata
      // This would typically come from the authentication provider
      const metadata = identity.entity?.metadata;
      setUserIdentity({
        customerId: metadata?.customerId as string,
      });
    });
  }, [identityApi]);

  const customerId = propCustomerId || userIdentity.customerId || 'default';
  
  // Generate customer-specific URLs
  const grafanaUrl = `https://grafana.container.mom/d/container-mom-deployments?orgId=${customerId}&var-customer=customer-${customerId}`;
  const logsUrl = `https://logs.container.mom/app/kibana#/discover?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))&_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'container-mom-customer-${customerId}-*',key:customer_id,negate:!f,params:(query:'${customerId}'),type:phrase),query:(match_phrase:(customer_id:'${customerId}')))),index:'container-mom-customer-${customerId}-*',interval:auto,query:(language:kuery,query:''),sort:!())`;
  const prometheusUrl = `https://prometheus.container.mom/graph?g0.expr=container_mom%3Acpu_usage%3Arate5m%7Bcustomer_id%3D%22${customerId}%22%7D&g0.tab=0`;

  return (
    <Card className={classes.card}>
      <CardHeader 
        title={MomText.observability?.title || "Kitchen Monitor"} 
        subheader={MomText.observability?.subtitle || "Keep an eye on your recipes"}
      />
      <CardContent>
        <Typography variant="subtitle2" className={classes.sectionTitle}>
          {MomText.observability?.metrics || "Recipe Metrics"}
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <Button
              href={grafanaUrl}
              target="_blank"
              rel="noopener noreferrer"
              variant="outlined"
              color="primary"
              className={classes.button}
              startIcon={<BarChartIcon className={classes.icon} />}
            >
              {MomText.observability?.viewMetrics || "View Kitchen Metrics"}
              <Typography variant="caption" style={{ marginLeft: 'auto' }}>
                Grafana
              </Typography>
            </Button>
          </Grid>
          
          <Grid item xs={12}>
            <Button
              href={prometheusUrl}
              target="_blank"
              rel="noopener noreferrer"
              variant="outlined"
              color="primary"
              className={classes.button}
              startIcon={<ShowChartIcon className={classes.icon} />}
            >
              {MomText.observability?.rawMetrics || "Raw Recipe Data"}
              <Typography variant="caption" style={{ marginLeft: 'auto' }}>
                Prometheus
              </Typography>
            </Button>
          </Grid>
        </Grid>

        <Typography variant="subtitle2" className={classes.sectionTitle}>
          {MomText.observability?.logs || "Kitchen Logs"}
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <Button
              href={logsUrl}
              target="_blank"
              rel="noopener noreferrer"
              variant="outlined"
              color="primary"
              className={classes.button}
              startIcon={<ListIcon className={classes.icon} />}
            >
              {MomText.observability?.viewLogs || "View Kitchen Logs"}
              <Typography variant="caption" style={{ marginLeft: 'auto' }}>
                Kibana
              </Typography>
            </Button>
          </Grid>
        </Grid>

        <Typography variant="caption" display="block" style={{ marginTop: 16 }}>
          Customer ID: {customerId}
        </Typography>
      </CardContent>
    </Card>
  );
};