import React, { useEffect, useState } from "react";
import { Page, Layouts } from "@strapi/strapi/admin";
import { Box, Button, Flex, Loader, Typography } from "@strapi/design-system";
import { presetsApi } from "../../utils/api";
import { applyStoredPresets } from "../../presets";
import { DEFAULT_STORED_TEMPLATE, createPresetDraft } from "../../presets/template";
import { BUILTIN_PRESET_NAMES, BUILTIN_STORED_PRESETS } from "../../presets/builtins";
import PresetList from "./PresetList.jsx";
import PresetEditor from "./PresetEditor.jsx";
import AISettingsPanel from "./AISettingsPanel.jsx";

const BUILTIN_ROWS = [
  { ...DEFAULT_STORED_TEMPLATE, name: "default", description: "CKStudio default preset" },
  ...BUILTIN_STORED_PRESETS,
];

const Settings = () => {
  const [presets, setPresets] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [editorState, setEditorState] = useState(null);
  const [showAiSettings, setShowAiSettings] = useState(false);
  const [notice, setNotice] = useState(null);

  const loadList = () =>
    presetsApi
      .list()
      .then(setPresets)
      .catch(() => setNotice({ type: "danger", text: "Failed to load presets" }));

  useEffect(() => {
    loadList().finally(() => setIsLoading(false));
  }, []);

  const handleCreate = () =>
    setEditorState({ isNew: true, draft: createPresetDraft(DEFAULT_STORED_TEMPLATE, "") });

  const handleEdit = (preset) =>
    setEditorState({ isNew: false, draft: createPresetDraft(preset, preset.name) });

  const handleDuplicate = (preset) => {
    const base = preset ?? DEFAULT_STORED_TEMPLATE;
    setEditorState({ isNew: true, draft: createPresetDraft(base, `${base.name || "default"}-copy`) });
  };

  const handleDelete = async (preset) => {
    const confirmed = window.confirm(`Delete preset "${preset.name}"? Fields using it will fall back to the default preset.`);
    if (!confirmed) return;

    try {
      await presetsApi.remove(preset.name);
      setNotice({ type: "success", text: `Preset "${preset.name}" deleted` });
      await loadList();
    } catch (error) {
      setNotice({ type: "danger", text: `Failed to delete: ${error.message}` });
    }
  };

  const handleSave = async (draft) => {
    try {
      const saved = await presetsApi.save(draft);
      applyStoredPresets([saved]);
      setNotice({
        type: "success",
        text: `Preset "${draft.name}" saved. Reload the admin to see it in new field settings.`,
      });
      setEditorState(null);
      await loadList();
    } catch (error) {
      setNotice({ type: "danger", text: `Failed to save: ${error.message}` });
    }
  };

  return (
    <Page.Main labelledBy="title">
      <Page.Title>CKStudio</Page.Title>
      <Layouts.Header
        id="title"
        title="CKStudio"
        subtitle="Editor presets: features, toolbar, colors and fonts"
      />
      <Layouts.Content>
        {notice && (
          <Box
            padding={3}
            marginBottom={4}
            hasRadius
            background={notice.type === "danger" ? "danger100" : "success100"}
          >
            <Typography textColor={notice.type === "danger" ? "danger600" : "success600"}>
              {notice.text}
            </Typography>
          </Box>
        )}
        {isLoading && <Loader />}
        {!isLoading && showAiSettings && <AISettingsPanel onClose={() => setShowAiSettings(false)} />}
        {!isLoading && !showAiSettings && !editorState && (
          <>
            <Flex justifyContent="flex-end" paddingBottom={2}>
              <Button variant="secondary" onClick={() => setShowAiSettings(true)}>
                AI settings
              </Button>
            </Flex>
            <PresetList
              presets={presets}
              builtinPresets={BUILTIN_ROWS}
              onCreate={handleCreate}
              onEdit={handleEdit}
              onDuplicate={handleDuplicate}
              onDelete={handleDelete}
            />
          </>
        )}
        {!isLoading && !showAiSettings && editorState && (
          <PresetEditor
            initialDraft={editorState.draft}
            isNew={editorState.isNew}
            existingNames={[...BUILTIN_PRESET_NAMES, ...presets.map((preset) => preset.name)]}
            onSave={handleSave}
            onCancel={() => setEditorState(null)}
          />
        )}
        <Flex marginTop={6} justifyContent="center">
          <Typography variant="pi" textColor="neutral500">
            CKStudio · CKEditor 5 preset studio for Strapi
          </Typography>
        </Flex>
      </Layouts.Content>
    </Page.Main>
  );
};

export default Settings;
