import { DeleteOutline, FileOpenOutlined } from "@mui/icons-material";
import { Box, Button, Stack, TextField } from "@mui/material";
import { open } from "@tauri-apps/api/dialog";
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 selected = await open({
      multiple: false,
      filters: [
        {
          name: "Images",
          extensions: ["jpg", "png", "jpeg", "webp", "gif"],
        },
      ],
    });

    if (selected) {
      console.log(selected);
    }
  };

  // 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>
  );
};
