import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Accordion,
  AccordionItem,
  AccordionHeader,
  AccordionPanel,
  Badge,
  Text,
} from "@fluentui/react-components";
import { DocumentAdd24Regular } from "@fluentui/react-icons";
import type { JailFileConfig, JailFileConfigUpdate, JailSectionConfig } from "../../types/config";
import { useAutoSave } from "../../hooks/useAutoSave";
import { AutoSaveIndicator } from "./AutoSaveIndicator";
import { useConfigStyles } from "./configStyles";
import { JailSectionPanel } from "./JailSectionPanel";

interface JailFileFormInnerProps {
  config: JailFileConfig;
  onSave: (update: JailFileConfigUpdate) => Promise<void>;
}

export function JailFileFormInner({ config, onSave }: JailFileFormInnerProps): React.JSX.Element {
  const [jails, setJails] = useState<Record<string, JailSectionConfig>>(config.jails);

  useEffect(() => {
    setJails(config.jails);
  }, [config]);

  const autoSavePayload = useMemo<JailFileConfigUpdate>(() => ({ jails }), [jails]);

  const { status: saveStatus, errorText: saveErrorText, retry: retrySave } = useAutoSave(autoSavePayload, onSave);

  const handleSectionChange = useCallback((jailName: string, next: JailSectionConfig): void => {
    setJails((prev) => ({ ...prev, [jailName]: next }));
  }, []);

  const styles = useConfigStyles();
  const jailNames = Object.keys(jails);

  return (
    <div>
      <div className={styles.buttonRow} style={{ marginBottom: 8 }}>
        <Text size={500} weight="semibold">{config.filename}</Text>
        <AutoSaveIndicator status={saveStatus} errorText={saveErrorText} onRetry={retrySave} />
      </div>

      {jailNames.length === 0 ? (
        <div className={styles.emptyState}>
          <DocumentAdd24Regular style={{ fontSize: 48, color: "var(--colorNeutralForeground3)" }} aria-hidden />
          <Text size={400} style={{ color: "var(--colorNeutralForeground3)" }}>
            No jail sections found in this file.
          </Text>
          <Text size={200} style={{ color: "var(--colorNeutralForeground3)" }}>
            Add a <code>[jailname]</code> section to the file to define jails.
          </Text>
        </div>
      ) : (
        <Accordion multiple collapsible defaultOpenItems={jailNames}>
          {jailNames.map((jailName) => {
            const section = jails[jailName];
            if (section === undefined) return null;
            return (
              <AccordionItem key={jailName} value={jailName} className={styles.accordionItem}>
                <AccordionHeader>
                  <Badge appearance="filled" color="informative" style={{ marginRight: 6 }}>
                    {jailName}
                  </Badge>
                  {section.enabled === true
                    ? "(enabled)"
                    : section.enabled === false
                    ? "(disabled)"
                    : ""}
                </AccordionHeader>
                <AccordionPanel>
                  <JailSectionPanel jailName={jailName} section={section} onChange={(next) => { handleSectionChange(jailName, next); }} />
                </AccordionPanel>
              </AccordionItem>
            );
          })}
        </Accordion>
      )}
    </div>
  );
}
