import { 
  ActionIcon, 
  Box, 
  Button, 
  Divider, 
  Group, 
  NativeSelect, 
  Stack, 
  Text, 
  Title 
} from '@mantine/core';
import { 
  SpotifyLogoIcon, 
  DevicesIcon, 
  SignOutIcon, 
  ArrowsClockwiseIcon 
} from '@phosphor-icons/react';
import { useSpotify } from '@/lib/spotify/hooks';
import { useAuth } from '@/contexts/auth-context';
import Sheet from '@/components/sheet/sheet';

interface SpotifySheetProps {
  opened: boolean;
  onClose: () => void;
}

const SpotifySheet: React.FC<SpotifySheetProps> = ({ opened, onClose }) => {
  const { roles } = useAuth();
  const isAdmin = roles?.includes('Admin') || false;
  const spotify = useSpotify();

  if (!isAdmin || !spotify) return null;
  const {
    isAuthenticated,
    login,
    logout,
    devices,
    activeDevice,
    currentTrack,
    getDevices,
    setActiveDevice,
    isLoading,
    error,
  } = spotify;

  if (!isAdmin) return null;

  const handleDeviceChange = (deviceId: string) => {
    if (deviceId && deviceId !== activeDevice?.id) {
      setActiveDevice(deviceId);
    }
  };

  const refreshDevices = () => {
    getDevices();
  };

  const handleChange = (opened: boolean) => {
    if (!opened) onClose();
  };

  return (
    <Sheet 
      opened={opened} 
      onChange={handleChange}
      title="Spotify Controls"
    >
          <Stack gap="lg">
            {!isAuthenticated ? (
              <>
                <Box>
                  <Text size="sm" c="dimmed" mb="md">
                    Connect your Spotify account
                  </Text>
                </Box>

                <Button
                  leftSection={<SpotifyLogoIcon size={20} />}
                  color="green"
                  size="lg"
                  onClick={login}
                  loading={isLoading}
                  fullWidth
                >
                  Connect with Spotify
                </Button>
              </>
            ) : (
              <>
                {/* Current track display */}
                {currentTrack && (
                  <>
                    <Box>
                      <Title order={5} mb="xs">Now Playing</Title>
                      <Group gap="md">
                        {currentTrack.album.images[2] && (
                          <img
                            src={currentTrack.album.images[2].url}
                            alt={currentTrack.album.name}
                            style={{ width: 64, height: 64, borderRadius: 4 }}
                          />
                        )}
                        <Box flex={1}>
                          <Text fw={600} size="sm" truncate>
                            {currentTrack.name}
                          </Text>
                          <Text size="xs" c="dimmed" truncate>
                            {currentTrack.artists.map(a => a.name).join(', ')}
                          </Text>
                          <Text size="xs" c="dimmed" truncate>
                            {currentTrack.album.name}
                          </Text>
                        </Box>
                      </Group>
                    </Box>
                    <Divider />
                  </>
                )}

                <Box>
                  <Group justify="space-between" align="center" mb="sm">
                    <Title order={5}>
                      <Group gap="xs">
                        <DevicesIcon size={20} />
                        Select Device
                      </Group>
                    </Title>
                    <ActionIcon
                      variant="light"
                      size="sm"
                      onClick={refreshDevices}
                      loading={isLoading}
                    >
                      <ArrowsClockwiseIcon size={16} />
                    </ActionIcon>
                  </Group>

                  {devices.length > 0 ? (
                    <NativeSelect
                      value={activeDevice?.id || ''}
                      onChange={(event) => handleDeviceChange(event.currentTarget.value)}
                      data={[
                        { value: '', label: 'Select a device...' },
                        ...devices.map(device => ({
                          value: device.id,
                          label: `${device.name} ${device.is_active ? '(Active)' : ''} - ${device.type}`,
                        })),
                      ]}
                      disabled={isLoading}
                    />
                  ) : (
                    <Text size="sm" c="dimmed">
                      No devices found.
                    </Text>
                  )}

                  {activeDevice && (
                    <Text size="xs" c="dimmed" mt="xs">
                      Active device: {activeDevice.name}
                      {activeDevice.volume_percent !== null && 
                        ` (Volume: ${activeDevice.volume_percent}%)`
                      }
                    </Text>
                  )}
                </Box>

                {error && (
                  <>
                    <Divider />
                    <Box>
                      <Text size="sm" c="red">
                        {error}
                      </Text>
                    </Box>
                  </>
                )}

                <Divider />
                <Button
                  leftSection={<SignOutIcon size={18} />}
                  variant="light"
                  color="red"
                  onClick={logout}
                  fullWidth
                >
                  Disconnect Spotify
                </Button>
              </>
            )}
          </Stack>
    </Sheet>
  );
};

export default SpotifySheet;