import React from "react";

import LocalOfferOutlinedIcon from "@mui/icons-material/LocalOfferOutlined";
import ReportIcon from "@mui/icons-material/Report";
import WarningIcon from "@mui/icons-material/Warning";
import { Grid2 as Grid, Stack, Typography } from "@mui/material";

import Card from "../../../components/Card";
import CardContent from "../../../components/Card/CardContent";
import CardHeader from "../../../components/Card/CardHeader";
import CardPill from "../../../components/Card/CardPill";
import Content from "../../../containers/Content";
import { ContribComponent } from "../../../types";
import { SiteItem, SiteItemsResponse } from "../types/contrib";

const parseStatus = (value: string | null | undefined): { label?: string; codes: string[] } => {
  if (!value) {
    return { codes: [] };
  }
  const trimmed = value.trim();
  const match = /^([^[]+)\[([^\]]*)\]>?$/.exec(trimmed);
  if (!match) {
    return { label: trimmed, codes: [] };
  }
  const [, label, codes] = match;
  return {
    label: label.trim(),
    codes: codes
      .split(",")
      .map((code) => code.trim())
      .filter(Boolean),
  };
};

const formatItem = (label: string, value: React.ReactNode) => (
  <Stack key={label} direction="row" justifyContent="space-between" spacing={2}>
    <Typography color="text.secondary" variant="body2">
      {label}
    </Typography>
    {typeof value === "string" || typeof value === "number" ? (
      <Typography variant="body2">{value}</Typography>
    ) : (
      value
    )}
  </Stack>
);

const ItemCard: React.FC<{ item: SiteItem }> = ({ item }) => {
  const { label: errorLabel, codes: errorCodes } = parseStatus(item.error);
  const { label: warningLabel, codes: warningCodes } = parseStatus(item.warning);

  return (
    <Card>
      <CardHeader title={item.site_code} />
      <CardContent>
        <Stack spacing={1}>
          {formatItem("Reference", item.reference)}
          {formatItem("Name", item.name)}
          {formatItem("Variant", item.variant || "—")}
          {formatItem(
            "Price",
            item.base_price !== item.price ? (
              <Stack alignItems="center" direction="row" spacing={1}>
                <Typography
                  color="text.disabled"
                  sx={{ textDecoration: "line-through" }}
                  variant="body2"
                >
                  {item.base_price} {item.currency}
                </Typography>
                <LocalOfferOutlinedIcon color="error" fontSize="small" />
                <Typography color="error" variant="body2">
                  {item.price} {item.currency}
                </Typography>
              </Stack>
            ) : (
              `${item.price} ${item.currency}`
            ),
          )}
          <Stack alignItems="center" alignSelf="flex-start" direction="row" flexWrap="wrap" gap={1}>
            {errorLabel && <CardPill color="error" icon={<ReportIcon />} label={errorLabel} />}
            {errorCodes.map((code) => (
              <CardPill
                key={`error-${code}`}
                color="error"
                icon={null}
                label={code}
                variant="outlined"
              />
            ))}
            {warningLabel && (
              <CardPill color="warning" icon={<WarningIcon />} label={warningLabel} />
            )}
            {warningCodes.map((code) => (
              <CardPill
                key={`warning-${code}`}
                color="warning"
                icon={null}
                label={code}
                variant="outlined"
              />
            ))}
            <CardPill
              color={item.is_available ? "success" : "warning"}
              label={item.is_available ? "Available" : "Unavailable"}
            />
          </Stack>
        </Stack>
      </CardContent>
    </Card>
  );
};

const SiteAvailability: ContribComponent<SiteItemsResponse> = ({ data }) => {
  const items = data.items ?? [];

  return (
    <Content layout="fullWidth">
      {items.length > 0 ? (
        <Grid container columns={12} spacing={2} width="100%">
          {items.map((item) => (
            <Grid key={`${item.site_code}-${item.reference}`} size={{ xs: 12, md: 4 }}>
              <Stack spacing={2}>
                <ItemCard item={item} />
              </Stack>
            </Grid>
          ))}
        </Grid>
      ) : (
        <Typography color="text.secondary" variant="body2">
          No items found
        </Typography>
      )}
    </Content>
  );
};

export default SiteAvailability;
