import { DeleteOutline, FileOpenOutlined } from "@mui/icons-material";
import { Box, Button, Stack, TextField } from "@mui/material";
import { open } from "@tauri-apps/api/dialog";
import { invoke } from "@tauri-apps/api/tauri";
import { useAtom } from "jotai";
import Image from "next/image";
import { FC } from "react";
import { stagedSettingsAtom } from "../../../../lib/store/jotai/settings";
import { CategoryTitle } from "../CategoryTitle";
import { SettingsItem } from "../SettingsItem";

interface SettingsTabBackgroundProps {
  sx?: any;
}

export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) => {
  // atoms
  const [stagedSettings, setStagedSettings] = useAtom(stagedSettingsAtom);

  const handleSettingsBackgroundValueChange = (
    settingKey: string,
    settingValue: boolean | number | string | number[],
  ) => {
    const newSettings = {
      ...stagedSettings,
      background: {
        ...stagedSettings.background,
        [settingKey]: settingValue,
      },
    };
    setStagedSettings(newSettings);
  };

  const selectImage = async () => {
    const { basename } = await import("@tauri-apps/api/path");

    let selectedFilePath = await open({
      multiple: false,
      filters: [
        {
          name: "Images",
          extensions: ["jpg", "png", "jpeg", "webp", "gif"],
        },
      ],
    });

    // if the user somehow manages to select multiple files, take the first file
    if (Array.isArray(selectedFilePath)) {
      selectedFilePath = selectedFilePath[0];
    }

    if (selectedFilePath) {
      try {
        // get the last filename from the path
        const filename = await basename(selectedFilePath);

        console.log(filename);
        console.log(selectedFilePath);

        // if there is already a wallpaper file, delete it
        if (stagedSettings.background.background_image_path) {
          try {
            await invoke("delete_old_wallpaper_image", {
              filePathString: stagedSettings.background.background_image_path,
            });
          } catch (error) {
            console.error("Failed to delete old wallpaper image", error);
          }
        }

        const destinationFilePath = (await invoke("process_wallpaper_image", {
          filePathString: selectedFilePath,
        })) as string;

        handleSettingsBackgroundValueChange("background_image_path", destinationFilePath);
      } catch (error) {
        console.error("deec nuts", error);
      }
    }
  };

  // TODO: implement
  const clearImage = async () => {};

  return (
    <Box sx={{ sx }}>
      <CategoryTitle title="Wallpaper" />
      <Box>
        <Image
          src="/wallpaper.jpg"
          alt="Image not found"
          width={200}
          height={200}
        />
      </Box>
      <Box
        sx={{
          mb: 2,
        }}
      >
        <Stack
          direction="row"
          spacing={1}
        >
          <Button
            color="primary"
            onClick={selectImage}
            startIcon={<FileOpenOutlined />}
            size="small"
            variant="outlined"
          >
            Select
          </Button>
          <Button
            color="warning"
            onClick={clearImage}
            startIcon={<DeleteOutline />}
            size="small"
            variant="outlined"
          >
            Clear
          </Button>
        </Stack>
      </Box>
      <CategoryTitle title="Colors" />
      <SettingsItem
        defaultText="#202124"
        description="Background color"
        input={
          <TextField
            name="background_color"
            onChange={(e) => {
              handleSettingsBackgroundValueChange(e.target.name, e.target.value);
            }}
            sx={{
              width: "100%",
            }}
            size="small"
            type="color"
            value={stagedSettings.background.background_color}
            variant="standard"
          />
        }
      />
    </Box>
  );
};
