import React from "react";
import { Box, FormControl, FormControlLabel, Switch, FormHelperText, ToggleButton, ToggleButtonGroup } from "@mui/material";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CancelIcon from "@mui/icons-material/Cancel";
import type { FieldConfig } from "../../../types";

interface Props {
  field: FieldConfig;
  value: any;
  onChange: (value: any) => void;
  nullable?: boolean;
}

export function BooleanField({ field, value, onChange, nullable }: Props) {
  if (nullable) {
    const strValue = String(value ?? "");
    return (
      <Box>
        <Box sx={{ fontSize: "0.75rem", color: "text.secondary", mb: 0.5, fontWeight: 600 }}>
          {field.label}
        </Box>
        <ToggleButtonGroup
          value={strValue}
          exclusive
          onChange={(_, v) => onChange(v ?? "")}
          size="small"
        >
          <ToggleButton value="" sx={{ color: "text.disabled", borderColor: "divider" }}>
            <Box sx={{ width: 16, height: 16, borderRadius: "50%", bgcolor: "action.disabledBackground" }} />
          </ToggleButton>
          <ToggleButton value="true" sx={{ color: "success.main", borderColor: "success.main" }}>
            <CheckCircleIcon fontSize="small" />
          </ToggleButton>
          <ToggleButton value="false" sx={{ color: "error.main", borderColor: "error.main" }}>
            <CancelIcon fontSize="small" />
          </ToggleButton>
        </ToggleButtonGroup>
      </Box>
    );
  }

  return (
    <FormControl component="fieldset" fullWidth size="small">
      <FormControlLabel
        control={
          <Switch
            checked={!!value}
            onChange={(e) => onChange(e.target.checked)}
            disabled={field.readOnly}
          />
        }
        label={field.label}
      />
      {field.description && <FormHelperText>{field.description}</FormHelperText>}
    </FormControl>
  );
}
