"use client";

import { App, Button, Card, Typography } from "antd";
import dynamic from "next/dynamic";
import type { ChangeEvent, ComponentType, CSSProperties } from "react";
import { useCallback, useEffect, useState } from "react";
import { getGlobalSettings, updateGlobalSettings } from "@/lib/api/settings";
import { ApiError } from "@/lib/api/client";

interface CodeEditorProps {
  value: string;
  language?: string;
  placeholder?: string;
  onChange?: (e: ChangeEvent<HTMLTextAreaElement>) => void;
  padding?: number;
  minHeight?: number;
  "data-color-mode"?: "dark" | "light";
  style?: CSSProperties;
  className?: string;
}

const CodeEditor = dynamic(() => import("@uiw/react-textarea-code-editor").then((mod) => mod.default), {
  ssr: false,
}) as ComponentType<CodeEditorProps>;

/**
 * Site-wide custom CSS, injected as a plain <style> tag in the root layout
 * (see apps/web/app/layout.tsx) - applies to every page, every user, no
 * per-role scoping. A code editor rather than a rich-text/WYSIWYG box since
 * this is raw CSS syntax, not formatted content.
 */
export function CustomCssTab() {
  const { message } = App.useApp();
  const [css, setCss] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const settings = await getGlobalSettings();
      setCss(settings.custom_css ?? "");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load settings.");
    } finally {
      setIsLoading(false);
    }
  }, [message]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  async function handleSave() {
    setIsSaving(true);
    try {
      await updateGlobalSettings({ custom_css: css || null });
      message.success("Custom CSS saved.");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't save that CSS.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <Card loading={isLoading} className="dms_settings_custom_css_card">
      <Typography.Paragraph type="secondary">
        Applied site-wide, on every page, for every user - loaded once at page load. Invalid CSS is applied as-is;
        the browser simply ignores any rule it can&apos;t parse.
      </Typography.Paragraph>
      <div style={{ border: "1px solid var(--ant-color-border, #d9d9d9)", borderRadius: 6, overflow: "hidden" }}>
        <CodeEditor
          value={css}
          language="css"
          placeholder=".my-class { color: red; }"
          onChange={(e: ChangeEvent<HTMLTextAreaElement>) => setCss(e.target.value)}
          padding={12}
          minHeight={320}
          data-color-mode="dark"
          style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 13 }}
          className="dms_settings_custom_css_editor"
        />
      </div>
      <Button type="primary" onClick={handleSave} loading={isSaving} style={{ marginTop: 16 }} className="dms_settings_custom_css_save_btn">
        Save
      </Button>
    </Card>
  );
}
