import React from "react";
import PropTypes from "prop-types";
import { Box, Button, Checkbox, Flex, Textarea, TextInput, Typography } from "@strapi/design-system";

const FontsTab = ({ config, onConfigChange, fonts, onFontsChange }) => {
  const fontFamily = config.fontFamily ?? { options: ["default"], supportAllValues: true };
  const fontSize = config.fontSize ?? { options: ["default"], supportAllValues: true };

  const handleFamiliesChange = (event) => {
    const options = event.target.value
      .split("\n")
      .map((line) => line.trim())
      .filter(Boolean);
    onConfigChange("fontFamily", { ...fontFamily, options });
  };

  const handleSizesChange = (event) => {
    const options = event.target.value
      .split(",")
      .map((entry) => entry.trim())
      .filter(Boolean)
      .map((entry) => (entry === "default" ? "default" : Number(entry) || entry));
    onConfigChange("fontSize", { ...fontSize, options });
  };

  const updateFont = (index, patch) =>
    onFontsChange(fonts.map((font, i) => (i === index ? { ...font, ...patch } : font)));

  const addFont = () => onFontsChange([...fonts, { family: "", cssUrl: "" }]);

  const removeFont = (index) => onFontsChange(fonts.filter((_, i) => i !== index));

  return (
    <Flex direction="column" alignItems="stretch" gap={6}>
      <Box>
        <Typography variant="sigma" textColor="neutral600">
          Custom web fonts
        </Typography>
        <Typography variant="pi" textColor="neutral500">
          Add a font family + its CSS URL (e.g. Google Fonts embed link with the weights you need).
          The font loads automatically in the editor and appears in the font dropdown. Load the SAME
          CSS on your public website so visitors see it too.
        </Typography>
        <Flex direction="column" alignItems="stretch" gap={2} paddingTop={3}>
          {fonts.map((font, index) => (
            <Flex key={index} gap={2} alignItems="center">
              <Box style={{ width: 220 }}>
                <TextInput
                  name={`font-family-${index}`}
                  value={font.family}
                  onChange={(event) => updateFont(index, { family: event.target.value })}
                  placeholder="Roboto"
                />
              </Box>
              <Box style={{ flex: 1 }}>
                <TextInput
                  name={`font-url-${index}`}
                  value={font.cssUrl}
                  onChange={(event) => updateFont(index, { cssUrl: event.target.value })}
                  placeholder="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
                />
              </Box>
              {font.family && font.cssUrl && (
                <Typography variant="pi" style={{ fontFamily: font.family, whiteSpace: "nowrap" }}>
                  Aa Bb 123
                </Typography>
              )}
              <Button variant="danger-light" onClick={() => removeFont(index)}>
                Remove
              </Button>
            </Flex>
          ))}
          {fonts.length === 0 && (
            <Typography variant="pi" textColor="neutral500">
              No custom fonts yet
            </Typography>
          )}
        </Flex>
        <Box paddingTop={2}>
          <Button variant="secondary" onClick={addFont}>
            Add custom font
          </Button>
        </Box>
      </Box>

      <Flex gap={6} alignItems="flex-start" wrap="wrap">
        <Box style={{ flex: 1, minWidth: 320 }}>
          <Typography variant="sigma" textColor="neutral600">
            Font family dropdown (one per line — custom fonts above are added automatically)
          </Typography>
          <Box paddingTop={2} paddingBottom={2}>
            <Textarea
              name="font-families"
              value={(fontFamily.options ?? []).join("\n")}
              onChange={handleFamiliesChange}
              placeholder={"default\nArial, Helvetica, sans-serif"}
              style={{ minHeight: 200, fontFamily: "monospace" }}
            />
          </Box>
          <Checkbox
            checked={fontFamily.supportAllValues !== false}
            onCheckedChange={(checked) =>
              onConfigChange("fontFamily", { ...fontFamily, supportAllValues: checked === true })
            }
          >
            Keep fonts not in this list when loading content
          </Checkbox>
        </Box>

        <Box style={{ flex: 1, minWidth: 320 }}>
          <Typography variant="sigma" textColor="neutral600">
            Font sizes (comma separated, use "default" for the base size)
          </Typography>
          <Box paddingTop={2} paddingBottom={2}>
            <Textarea
              name="font-sizes"
              value={(fontSize.options ?? []).join(", ")}
              onChange={handleSizesChange}
              placeholder="10, 12, 14, default, 18, 20, 24"
              style={{ minHeight: 60, fontFamily: "monospace" }}
            />
          </Box>
          <Checkbox
            checked={fontSize.supportAllValues !== false}
            onCheckedChange={(checked) =>
              onConfigChange("fontSize", { ...fontSize, supportAllValues: checked === true })
            }
          >
            Keep sizes not in this list when loading content
          </Checkbox>
          <Box paddingTop={4}>
            <Typography variant="pi" textColor="neutral500">
              Font weights come from the loaded font file — include the weights you need in the CSS
              URL (Google Fonts: wght@300;400;700). Bold in the editor uses the 700 weight.
            </Typography>
          </Box>
        </Box>
      </Flex>
    </Flex>
  );
};

FontsTab.propTypes = {
  config: PropTypes.object.isRequired,
  onConfigChange: PropTypes.func.isRequired,
  fonts: PropTypes.array.isRequired,
  onFontsChange: PropTypes.func.isRequired,
};

export default FontsTab;
