import { useEffect, useState } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { exportJson } from '@components/Settings/SettingHelpers';
import {
  Button,
  FormFileUpload,
  Notice,
  TextControl,
  ToggleControl,
} from '@wordpress/components';
import type { ResponseProps } from '@components/DesignPanel/types';

import { TabsWrapper, TabsList, TabsContent } from '@components/ui/Tabs';
import { PasswordInput } from '@components/ui/PasswordInput';

import PageIcon from 'blockbite-icons/dist/Pencil1';
import { Icon as IconComp } from '@components/ui/Icon';

type findReplaceType = {
  from: string;
  to: string;
};

export const SynchronisationPanel = () => {
  const [message, setMessage] = useState<string>('');
  const [findReplace, setFindReplace] = useState<findReplaceType>({
    from: '',
    to: '',
  });
  const [currentVersion] = useState<string>(wpApiSettings.itemsVersion);
  const [isSwiperEnabled, setIsSwiperEnabled] = useState(false);
  const [openAiKey, setOpenAiKey] = useState<string>('');

  useEffect(() => {
    // Fetch the initial state from the server
    const fetchLibrarySettings = async () => {
      const response = await apiFetch({
        path: '/blockbite/v1/settings/swiper',
      });

      setIsSwiperEnabled((response as any).isSwiperEnabled);
    };

    // Fetch openai key
    const fetchOpenAiKey = async () => {
      const response = await apiFetch({
        path: '/blockbite/v1/settings/openai_key',
      });

      setOpenAiKey((response as any)?.key || '');
    };

    fetchLibrarySettings();
    fetchOpenAiKey();
  }, []);

  /*
    Export items to json file
    And generate download
  */
  const handleExport = async (handle: string) => {
    try {
      const response = await apiFetch({
        path: `/blockbite/v1/settings/site/sync-items?handle=${handle}`,
        method: 'GET',
      });
      exportJson(response, handle);
    } catch (error) {
      console.error(error);
    }
  };

  /*
    Import items from json file
  */
  const handleImport = async (event: any, handle: string) => {
    const file = event.currentTarget.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('handle', handle);

    try {
      const response = (await apiFetch({
        path: `/blockbite/v1/settings/site/sync-items`,
        method: 'POST',
        body: formData,
      })) as ResponseProps;
      if (response.status === 200) {
        setMessage('Preset imported successfully');
      }
    } catch (error) {
      console.error(error);
    }
  };

  /*
    Sync blockbite core items into the database
  */
  const handleSync = async (handle: string) => {
    try {
      const response = await apiFetch({
        path: `/blockbite/v1/settings/blockbite/sync-items`,
        method: 'POST',
        data: {
          version: currentVersion,
          handle: handle,
          platform: 'blockbite',
        },
      });
      exportJson(response, 'preset');
    } catch (error) {}
  };

  /*
    Sync templates folder within theme
    Creates a new folder called migrated-templates and copies all the templates and template-parts
  */
  const handleMigrateTemplates = async () => {
    try {
      const response = (await apiFetch({
        path: `/blockbite/v1/settings/migrate-templates`,
        method: 'POST',
        data: {
          find: findReplace.from,
          replace: findReplace.to,
        },
      })) as ResponseProps;
      setMessage(response.message);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSwiperToggle = async () => {
    try {
      await apiFetch({
        path: '/blockbite/v1/settings/swiper',
        method: 'POST',
        data: { isSwiperEnabled: !isSwiperEnabled },
      });

      setIsSwiperEnabled(!isSwiperEnabled);
      setMessage('Settings updated successfully');
    } catch (error) {
      console.error('Failed to update setting:', error);
    }
  };

  const handleOpenAiKeySubmit = async () => {
    if (!openAiKey) {
      setMessage('Please enter an OpenAI API key');
      return;
    }
    try {
      await apiFetch({
        path: '/blockbite/v1/settings/openai_key',
        method: 'POST',
        data: { key: openAiKey },
      });

      setMessage('Settings updated successfully');
    } catch (error) {
      console.error('Failed to update setting:', error);
    }
  };

  return (
    <>
      {message && (
        <Notice
          status="info"
          key={message}
          onDismiss={() => {
            setMessage('');
          }}
        >
          {message}
        </Notice>
      )}
      <div className="synchronisation-panel mt-4 max-w-prose">
        <TabsWrapper defaultValue="preset">
          <TabsList
            className="mb-4 max-w-[500px]"
            options={[
              { name: 'preset', title: 'Preset' },
              { name: 'templates', title: 'Templates' },
              { name: 'tokens', title: 'Tokens' },
              { name: 'libraries', title: 'Libraries' },
              { name: 'integrations', title: 'Integrations' },
            ]}
          ></TabsList>
          <TabsContent value="preset">
            <div className="flex items-center gap-3">
              <div>
                <Button
                  variant="secondary"
                  icon={<IconComp icon={PageIcon} />}
                  onClick={() => handleExport('preset')}
                >
                  Export Presets
                </Button>
              </div>
              <div>
                <FormFileUpload
                  accept="json"
                  icon={<IconComp icon={PageIcon} />}
                  onChange={(event) => handleImport(event, 'preset')}
                >
                  Import Presets
                </FormFileUpload>
              </div>
            </div>
            <div className="my-4">
              <h4 className="font-semibold">Sync Blockbite Presets</h4>
              <p>Synchronize Blockbite presets to your preset panel</p>
            </div>
            <div className="flex items-center gap-3">
              <Button
                variant="primary"
                icon={<IconComp icon={PageIcon} />}
                onClick={() => handleSync('preset')}
              >
                Sync
              </Button>
              <span>Current version: {currentVersion}</span>
            </div>
          </TabsContent>
          <TabsContent value="tokens">
            <div className="flex items-center gap-3">
              <div>
                <Button
                  variant="secondary"
                  icon={<IconComp icon={PageIcon} />}
                  onClick={() => handleExport('design-tokens')}
                >
                  Export Tokens
                </Button>
              </div>
              <div>
                <FormFileUpload
                  accept="json"
                  icon={<IconComp icon={PageIcon} />}
                  onChange={(event) => handleImport(event, 'design-tokens')}
                >
                  Import Tokens
                </FormFileUpload>
              </div>
            </div>
            <div className="my-4">
              <h4 className="font-semibold">Sync Blockbite Tokens</h4>
              <p>Synchronize Blockbite tokens to your preset panel</p>
            </div>
            <div className="flex items-center gap-3">
              <Button
                variant="primary"
                icon={<IconComp icon={PageIcon} />}
                onClick={() => handleSync('design-tokens')}
              >
                Sync
              </Button>
              <span>Current version: {currentVersion}</span>
            </div>
          </TabsContent>
          <TabsContent value="templates">
            <p>
              Exports Blockbite templates to your theme within a new folder
              called
              <br />
              <span className="font-medium">migrated-templates</span>
            </p>
            <p className="my-4 font-medium">Find and replace theme name</p>
            <TextControl
              label="Find"
              value={findReplace.from}
              onChange={(value) =>
                setFindReplace({ ...findReplace, from: value })
              }
            />
            <TextControl
              label="Replace"
              value={findReplace.to}
              onChange={(value) =>
                setFindReplace({ ...findReplace, to: value })
              }
            />
            <div className="mt-4">
              <Button
                variant="primary"
                icon={<IconComp icon={PageIcon} />}
                onClick={() => handleMigrateTemplates()}
              >
                Export
              </Button>
            </div>
          </TabsContent>
          <TabsContent value="libraries">
            <div className="max-w-sm pb-4">
              <ToggleControl
                checked={isSwiperEnabled}
                onChange={handleSwiperToggle}
                label="Import Swiper library"
                help="The Swiper library is required for the Blockbite Carousel block. If you don't need the Carousel block, or if you already have Swiper imported for your project, you can disable this option."
              />
            </div>
          </TabsContent>
          <TabsContent value="integrations">
            <p className="mb-4">
              Connect your Blockbite account with third-party integrations
            </p>
            <PasswordInput
              label="OpenAI API Key"
              value={openAiKey}
              onChange={setOpenAiKey}
              className="mb-4"
            />
            <Button
              icon={<IconComp icon={PageIcon} />}
              variant="primary"
              onClick={handleOpenAiKeySubmit}
            >
              Connect
            </Button>
          </TabsContent>
        </TabsWrapper>
      </div>
    </>
  );
};

export default SynchronisationPanel;
