import React, { useState } from "react";
import { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../../types";
import { applyDisplayFormat } from "../utils";
import { extractFields } from "../../../transformers/field-config";
import { useAppContext } from "../../../context/AppContext";


interface Props {
  field: FieldConfig;
  value: any;
}

const displayLabels: Record<string, string> = {
  basic: "Basic",
  heart_rate: "Heart Rate",
  dental: "Dental",
  vaccine: "Vaccine",
  preop: "PreOp",
  surgery: "Surgery",
};

export function InlineRefField({ field, value }: Props) {
  const [open, setOpen] = useState(false);
  const { schemas } = useAppContext();

  if (!value || typeof value !== "object") {
    return <Typography variant="body2" color="text.disabled">—</Typography>;
  }

  const discProp = field.discriminatorProperty;
  const discValue = discProp ? value[discProp] : undefined;
  const discChip = discValue ? displayLabels[discValue] ?? discValue : undefined;
  const tooltip = field.inlineDisplayFormat
    ? applyDisplayFormat(value, field.inlineDisplayFormat)
    : undefined;

  const schema = field.refSchema ? schemas[field.refSchema] : undefined;
  let subFields: FieldConfig[] = [];
  if (field.oneOfOptions && field.discriminatorProperty) {
    const activeOption = field.oneOfOptions.find((o) => o.value === value[field.discriminatorProperty!]);
    if (activeOption) subFields = activeOption.fields;
  } else if (schema && field.refSchema) {
    subFields = extractFields(field.refSchema, schema, schemas);
  }

  return (
    <>
      <Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap", alignItems: "center" }}>
        {discChip && <Chip label={discChip} size="small" color="primary" variant="outlined" />}
        <Chip
          label={field.label}
          title={tooltip}
          size="small"
          color="primary"
          variant="outlined"
          onClick={() => setOpen(true)}
          sx={{ cursor: "pointer" }}
        />
      </Box>
      <Dialog open={open} onClose={() => setOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{field.label}</DialogTitle>
        <DialogContent dividers>
          <Grid container spacing={2} sx={{ mt: 0.5 }}>
            {subFields.map((sf) => (
              <Grid key={sf.name} item xs={12} sm={6}>
                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
                    {sf.label}
                  </Typography>
                  <Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : String(value[sf.name])}</Typography>
                </Box>
              </Grid>
            ))}
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
