"use client";

import axios from "axios";
import * as React from 'react';
import { Check, ChevronsUpDown } from "lucide-react"
import { useEffect, useReducer, useState } from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "@/components/ui/command"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import voices from "@/data/tts";
import InfoNotice from "@/components/elements/info-notice";

const TTSVoiceFiltersPage = () => {
  const [open, setOpen] = useState(false)
  const [defaultVoice, setDefaultVoice] = useState("")
  const [loading, setLoading] = useState(true)

  function enabledVoicesReducer(enabledVoices: { [voice: string]: boolean }, action: { type: string, value: string }) {
    if (action.type == "enable") {
        return { ...enabledVoices, [action.value]: true }
    } else if (action.type == "disable") {
        return { ...enabledVoices, [action.value]: false }
    }
    return enabledVoices
  }

  const [enabledVoices, dispatchEnabledVoices] = useReducer(enabledVoicesReducer, Object.assign({}, ...voices.map(v => ({[v]: false}) )))

  useEffect(() => {
    axios.get("/api/settings/tts/default")
      .then((voice) => {
        setDefaultVoice(voice.data)
      })
    
    axios.get("/api/settings/tts")
      .then((d) => {
        const data: string[] = d.data;
        data.forEach(d => dispatchEnabledVoices({ type: "enable", value: d }))
        setLoading(false)
      })
  }, [])

  const onDefaultChange = (voice: string) => {
    try {
      axios.post("/api/settings/tts/default", { voice })
        .catch(e => console.error(e))
    } catch (error) {
      console.log("[TTS/DEFAULT]", error);
    }
  }

  const onEnabledChanged = (voice: string, state: boolean) => {
    try {
      axios.post("/api/settings/tts", { voice: voice, state: state })
        .catch(e => console.error(e))
    } catch (error) {
      console.log("[TTS/ENABLED]", error);
    }
  }

  return ( 
    <div>
      <div className="text-2xl text-center pt-[50px]">TTS Voices</div>
      <div className="px-10 py-10 w-full h-full flex-grow">
        <div className="flex flex-row justify-evenly">
          <div>
            <div className="inline-block text-lg">Default Voice</div>
            <Label className="pl-[10px] inline-block">Voice used without any voice modifiers</Label>
          </div>
          <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                role="combobox"
                aria-expanded={open}
                className="w-[200px] justify-between">
                {defaultVoice ? voices.find(v => v == defaultVoice) : "Select voice..."}
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[200px] p-0">
              <Command>
                <CommandInput placeholder="Search voice..." />
                <CommandEmpty>No voices found.</CommandEmpty>
                <CommandGroup>
                  {voices.map((voice) => (
                    <CommandItem
                      key={voice}
                      value={voice}
                      onSelect={(currentVoice) => {
                        setDefaultVoice(voice)
                        onDefaultChange(voice)
                        setOpen(false)
                      }}>
                      <Check
                        className={cn(
                          "mr-2 h-4 w-4",
                          defaultVoice === voice ? "opacity-100" : "opacity-0"
                        )}
                      />
                      {voice}
                    </CommandItem>
                  ))}
                </CommandGroup>
              </Command>
            </PopoverContent>
          </Popover>
        </div>

        <div className="w-full pt-[50px]">
          <p className="text-xl text-center justify-center">Voices Enabled</p>
          <InfoNotice message="Voices can be disabled from being used. Default voice will always work." hidden={false} />
          <div className="grid grid-cols-4 grid-flow-row gap-4 pt-[20px]">
            {voices.map((v, i) => (
              <div key={v + "-enabled"} className="h-[30px] row-span-1 col-span-1 align-middle flex items-center justify-center">
                <Checkbox onClick={() => {
                  dispatchEnabledVoices({ type: enabledVoices[v] ? "disable" : "enable", value: v })
                  onEnabledChanged(v, !enabledVoices[v])
                }}
                disabled={loading}
                checked={enabledVoices[v]} />
                <div className="pl-[5px]">{v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
   );
}
 
export default TTSVoiceFiltersPage;