import React from "react";
import { Box, Typography, Chip, Avatar } from "@mui/material";
import type { FieldConfig } from "../../types";
import { applyDisplayFormat } from "./utils";
import { InlineRefField } from "./renderers/InlineRefField";

interface ListCellProps {
  field: FieldConfig;
  value: any;
  displayFormat?: string;
}

export function ListCellRenderer({ field, value, displayFormat }: ListCellProps) {
  if (value === null || value === undefined) {
    return <Typography variant="body2" color="text.disabled">—</Typography>;
  }

  if (field.refSchema && !field.fk && !field.isArray && typeof value === "object") {
    return <InlineRefField field={field} value={value} displayFormat={displayFormat} />;
  }

  if (field.isArray && Array.isArray(value) && field.refSchema && !field.fk) {
    if (value.length === 0) {
      return <Typography variant="body2" color="text.disabled">—</Typography>;
    }
    return (
      <Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
        {value.map((item: any, i: number) => {
          const label = typeof item === "object"
            ? applyDisplayFormat(item, displayFormat ?? "")
            : String(item);
          return <Chip key={i} label={label} size="small" variant="outlined" />;
        })}
      </Box>
    );
  }

  if (field.fk && typeof value === "object" && !field.isArray) {
    return <Typography variant="body2">{applyDisplayFormat(value, displayFormat ?? "")}</Typography>;
  }

  if (field.isArray && Array.isArray(value) && field.fk) {
    return (
      <Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
        {value.map((item: any, i: number) => {
          const label = typeof item === "object" ? applyDisplayFormat(item, displayFormat ?? "") : String(item);
          return <Chip key={i} label={label} size="small" variant="outlined" />;
        })}
      </Box>
    );
  }

  if (field.enumValues) {
    return <Chip label={value} size="small" />;
  }

  if (field.uiType === "image" && value) {
    return <Avatar src={value} variant="rounded" sx={{ width: 40, height: 40 }} />;
  }

  if (field.type === "boolean") {
    return <Chip label={value ? "Yes" : "No"} size="small" color={value ? "success" : "default"} />;
  }

  return <Typography variant="body2">{String(value)}</Typography>;
}
