'use client';

import {
  getGuilds,
  getTextChannels,
  getVoiceChannels,
  getVolume,
  pauseTrack,
  playTrack,
  resumeTrack,
  sendMessage,
  setVolume,
  skipTrack,
  stopTrack
} from '@/api/guilds';
import { GuildChannel, GuildInfo } from '@/api/guilds.types';
import Auth from '@/components/Auth';
import { userState } from '@/state/auth';
import { Button, Card, Grid, Select, Slider, Tabs, TextInput, Textarea } from '@mantine/core';
import { useForm } from '@mantine/form';
import { useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';
import { useRecoilValue } from 'recoil';

function Page() {
  const user = useRecoilValue(userState);
  const [guilds, setGuilds] = useState<GuildInfo[]>([]);
  const [activeGuild, setActiveGuild] = useState<GuildInfo | null>(null);
  const router = useRouter();

  useEffect(() => {
    // Check if the user is logged in and an admin, otherwise redirect to the home page
    // if (!user || !user.roles.includes('admin')) {
      if (!user || user.role !== 'admin') {
      router.push('/');
    } else {
      getGuilds().then((g) => {
        setGuilds(g);
        if (g.length > 0) {
          setActiveGuild(g[0]);
        }
      });
    }
  }, []);

  return (
    <Tabs orientation='vertical' defaultValue={activeGuild?.name}>
      <Tabs.List>
        {guilds && guilds.map((guild) => (
          <Tabs.Tab key={`guild-tab-${guild.id}`} value={guild.name} onClick={() => setActiveGuild(guild)}>
            {guild.name}
          </Tabs.Tab>
        ))}
      </Tabs.List>
      {guilds && guilds.map((guild) => (
        <Tabs.Panel key={`guild-${guild.id}`} value={guild.name}>
          <h1>{guild.name}</h1>
          <Grid>
            <Grid.Col span={6}>
              <TextChannelCard guild={activeGuild} />
            </Grid.Col>
            <Grid.Col span={6}>
              <VoiceChannelsCard guild={activeGuild} />
            </Grid.Col>
          </Grid>
        </Tabs.Panel>
      ))}
    </Tabs>
  );
}

export default Auth(Page);

function TextChannelCard({ guild }: { guild: GuildInfo | null }) {
  const [textChannels, setTextChannels] = useState<GuildChannel[]>([]);
  const [activeChannel, setActiveChannel] = useState<GuildChannel | null>(null);

  const form = useForm({
    initialValues: {
      message: ''
    }
  });

  useEffect(() => {
    if (guild) {
      getTextChannels(guild.id).then((c) => setTextChannels(c));
    }
  }, [guild]);

  return (
    <Card shadow='sm' style={{ margin: '1em' }}>
      <Card.Section>
        <h2>Text Channels</h2>
        <Select
          placeholder='Select channel...'
          data={textChannels.map((channel, index) => {
            return {
              value: `${index}`,
              label: channel.name
            };
          })}
          onChange={(e) => {
            if (e) {
              setActiveChannel(textChannels[parseInt(e)]);
            }
          }}
        />
        {activeChannel && (
          <form
            style={{ margin: '1em' }}
            onSubmit={form.onSubmit((values) => {
              sendMessage(guild!.id, activeChannel.id, values.message);
            })}
          >
            <Textarea placeholder='Message...' {...form.getInputProps('message')} />
            <Button type='submit'>Send Message</Button>
          </form>
        )}
      </Card.Section>
    </Card>
  );
}

function VoiceChannelsCard({ guild }: { guild: GuildInfo | null }) {
  const [voiceChannels, setVoiceChannels] = useState<GuildChannel[]>([]);
  const [guildVolume, setGuildVolume] = useState<number>(50.0);
  const [activeChannel, setActiveChannel] = useState<GuildChannel | null>(null);

  useEffect(() => {
    if (guild) {
      getVoiceChannels(guild.id).then((c) => setVoiceChannels(c));
      getVolume(guild.id).then((v) => setGuildVolume(v));
    }
  }, [guild]);

  const form = useForm({
    initialValues: {
      trackUrl: '',
      volume: 50.0
    }
  });

  return (
    <Card shadow='sm' style={{ margin: '1em' }}>
      <Card.Section>
        <h2>Voice Channels</h2>
        <Select
          placeholder='Select channel...'
          data={voiceChannels.map((channel, index) => {
            return {
              value: `${index}`,
              label: channel.name
            };
          })}
          onChange={(e) => {
            if (e) {
              setActiveChannel(voiceChannels[parseInt(e)]);
            }
          }}
        />
        {activeChannel && (
          <>
            <form
              style={{ margin: '1em' }}
              onSubmit={form.onSubmit((values) => setVolume(guild!.id, values.volume))}
            >
              <Slider
                defaultValue={guildVolume}
                {...form.getInputProps('volume')}
                marks={[
                  { value: 25, label: '25%' },
                  { value: 50, label: '50%' },
                  { value: 75, label: '75%' }
                ]}
              />
              <Button type='submit'>Set Volume</Button>
            </form>
            <form
              style={{ margin: '1em' }}
              onSubmit={form.onSubmit((values) => playTrack(guild!.id, activeChannel.id, values.trackUrl))}
            >
            <TextInput placeholder='Youtube URL...' />
            <Button type='submit'>Play Track</Button>
          </form>
          <div style={{ margin: '1em' }}>
                  <Button style={{ marginRight: '1em' }} onClick={() => skipTrack(guild!.id)}>
                    Skip Track
                  </Button>
                  <Button style={{ marginRight: '1em' }} onClick={() => stopTrack(guild!.id)}>
                    Stop
                  </Button>
                  <Button style={{ marginRight: '1em' }} onClick={() => pauseTrack(guild!.id)}>
                    Pause
                  </Button>
                  <Button style={{ marginRight: '1em' }} onClick={() => resumeTrack(guild!.id)}>
                    Resume
                  </Button>
                </div>
          </>
        )}
      </Card.Section>
    </Card>
  );
}
