import { BatteryCharge, Refresh } from "@icon-park/react"
import { invoke } from "@tauri-apps/api/core"
import { Card, CardBody, CardHeader, CardIcon, CardTool } from "../window/Card"
import { ToolButton } from "../window/ToolButton"
import { Tabs, Tab, addToast } from "@heroui/react"
import { Key } from "@react-types/shared"
import { useToolStore } from "@/store/tool"
import { useEffect } from "react"

const PowerPlans = [
  {
    id: "0",
    title: "其他",
  },
  {
    id: "1",
    title: "节能",
  },
  {
    id: "2",
    title: "平衡",
  },
  {
    id: "3",
    title: "高性能",
  },
  {
    id: "4",
    title: "卓越性能",
  },
]

const PowerPlan = () => {
  const tool = useToolStore()
  const setPowerPlan = async (key: Key) => {
    await tool.store.start()
    const plan = Number(key)

    await invoke("set_powerplan", { plan: plan })
    const current = await invoke<number>("get_powerplan")
    tool.setPowerPlan(current)

    addToast({ title: `电源计划已切换 → ${  PowerPlans[current].title}` })
  }

  const getPowerPlan = async (toast: boolean) => {
    await tool.store.start()
    const current = await invoke<number>("get_powerplan")
    tool.setPowerPlan(current)

    if (toast) addToast({ title: `电源计划已切换 → ${  PowerPlans[current].title}` })
  }

  useEffect(() => {
    void getPowerPlan(false)
  }, [])

  return (
    <Card>
      <CardHeader>
        <CardIcon>
          <BatteryCharge /> 电源计划
        </CardIcon>
        <CardTool>
          <ToolButton onClick={() => getPowerPlan(true)}>
            <Refresh />
            刷新
          </ToolButton>
        </CardTool>
      </CardHeader>
      <CardBody>
        <Tabs
          selectedKey={String(tool.state.powerPlan)}
          onSelectionChange={setPowerPlan}
          aria-label="Power Plan Tabs"
          size="md"
          radius="full"
          fullWidth
          defaultSelectedKey="0"
        >
          {PowerPlans.slice(1).map((item) => (
            <Tab key={item.id} title={item.title}></Tab>
          ))}
        </Tabs>
      </CardBody>
    </Card>
  )
}

export default PowerPlan
