"use client";

import { App, Card, Popconfirm, Switch, Typography } from "antd";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { getGlobalSettings, setDemoMode, updateGlobalSettings } from "@/lib/api/settings";
import { ApiError } from "@/lib/api/client";
import { useSiteBranding } from "@/lib/branding/BrandingProvider";
import { notifyAssistantEnabledChanged } from "@/lib/utils/assistantSettings";

export function ExtraTab() {
  const { message } = App.useApp();
  const branding = useSiteBranding();
  const [assistantEnabled, setAssistantEnabled] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const router = useRouter();
  const [demoEnabled, setDemoEnabled] = useState(false);
  const [isSavingDemo, setIsSavingDemo] = useState(false);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const settings = await getGlobalSettings();
      setAssistantEnabled(settings.assistant_enabled);
      setDemoEnabled(settings.demo_mode);
    } 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 handleToggle(checked: boolean) {
    setIsSaving(true);
    try {
      const updated = await updateGlobalSettings({ assistant_enabled: checked });
      setAssistantEnabled(updated.assistant_enabled);
      notifyAssistantEnabledChanged(updated.assistant_enabled);
      message.success(checked ? "Assistant enabled." : "Assistant disabled.");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't change that setting.");
    } finally {
      setIsSaving(false);
    }
  }

  async function handleDemoToggle(checked: boolean) {
    setIsSavingDemo(true);
    try {
      const result = await setDemoMode(checked);
      setDemoEnabled(result.demo_mode);
      message.success(checked ? "Demo content is on." : "Demo content removed.");
      router.refresh();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't change demo content.");
    } finally {
      setIsSavingDemo(false);
    }
  }

  const demoDescription = (
    <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
      Fills the site with a fixed set of sample content: one Namecheap registrar account, a Demo project across MY, SG, TH,
      ID and VN, one demo server, one demo Cloudflare account, and eight domains with subdomains. A notice bar shows on
      every page while it is on. Turning it off removes only that sample content - never anything you added yourself.
    </Typography.Paragraph>
  );

  return (
    <div className="flex flex-col gap-4">
    <Card loading={isLoading} className="dms_settings_extra_assistant_card">
      <div className="flex items-center gap-3">
        <Switch checked={assistantEnabled} loading={isSaving} onChange={handleToggle} />
        <div>
          <Typography.Text strong>{branding.site_title} Assistant</Typography.Text>
          <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
            Site-wide on/off switch for the chat assistant widget in the dashboard. Turning it off hides it for
            every user.
          </Typography.Paragraph>
        </div>
      </div>
    </Card>

    <Card loading={isLoading} className="dms_settings_extra_demo_card">
      <div className="flex items-start gap-3">
        {demoEnabled ? (
          <Popconfirm
            title="Remove the demo content?"
            description="The sample records are deleted, along with any changes made to them."
            okText="Remove"
            onConfirm={() => void handleDemoToggle(false)}
          >
            <Switch checked loading={isSavingDemo} className="dms_settings_extra_demo_switch" />
          </Popconfirm>
        ) : (
          <Switch checked={false} loading={isSavingDemo} onChange={(checked) => void handleDemoToggle(checked)} className="dms_settings_extra_demo_switch" />
        )}
        <div>
          <Typography.Text strong>Show demo content</Typography.Text>
          {demoDescription}
        </div>
      </div>
    </Card>
    </div>
  );
}
