import React, { useState, useEffect } from 'react';
import {
  Paper,
  TextInput,
  Button,
  Group,
  Stack,
  Title,
  ActionIcon,
  ScrollArea,
  Box,
  Select,
  Alert,
  Code,
  Divider,
  Text,
  Modal,
} from '@mantine/core';
import { IconX, IconCheck, IconCopy } from '@tabler/icons-react';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import PermissionTree from './PermissionTree';
import {
  apiService,
  Application,
  CreateTokenRequest,
  CreateTokenResponse,
} from '../services/apiService';

interface TokenSidebarProps {
  opened: boolean;
  onClose: () => void;
  onSuccess: () => void;
  applications: Application[];
}

const TokenSidebar: React.FC<TokenSidebarProps> = ({
  opened,
  onClose,
  onSuccess,
  applications,
}) => {
  const [tokenModalOpen, setTokenModalOpen] = useState(false);
  const [createdToken, setCreatedToken] = useState<CreateTokenResponse | null>(null);

  const form = useForm<CreateTokenRequest & { app_id: string }>({
    initialValues: {
      app_id: '',
      owner: {
        type: 'individual',
        name: 'Admin User',
        owner: 'admin@example.com',
      },
      permissions: [],
    },
    validate: {
      app_id: (value) => value.length < 1 ? 'Application is required' : null,
      permissions: (value) => value.length < 1 ? 'At least one permission is required' : null,
    },
  });

  // Reset form when sidebar opens
  useEffect(() => {
    if (opened) {
      form.reset();
    }
  }, [opened]);

  const handleSubmit = async (values: CreateTokenRequest & { app_id: string }) => {
    try {
      const { app_id, ...tokenData } = values;
      const response = await apiService.createToken(app_id, tokenData);
      setCreatedToken(response);
      setTokenModalOpen(true);
      form.reset();
      onSuccess();
      notifications.show({
        title: 'Success',
        message: 'Token created successfully',
        color: 'green',
      });
    } catch (error) {
      console.error('Failed to create token:', error);
      notifications.show({
        title: 'Error',
        message: 'Failed to create token',
        color: 'red',
      });
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    notifications.show({
      title: 'Copied',
      message: 'Copied to clipboard',
      color: 'blue',
    });
  };

  const handleTokenModalClose = () => {
    setTokenModalOpen(false);
    setCreatedToken(null);
    onClose();
  };

  return (
    <>
      <Paper
        style={{
          position: 'fixed',
          top: 60, // Below header
          right: opened ? 0 : '-450px',
          bottom: 0,
          width: '450px',
          zIndex: 1000,
          borderRadius: 0,
          display: 'flex',
          flexDirection: 'column',
          borderLeft: '1px solid var(--mantine-color-gray-3)',
          backgroundColor: 'var(--mantine-color-body)',
          transition: 'right 0.3s ease',
        }}
      >
        {/* Header */}
        <Group justify="space-between" p="md" style={{ borderBottom: '1px solid var(--mantine-color-gray-3)' }}>
          <Title order={4}>
            Create New Token
          </Title>
          <ActionIcon
            variant="subtle"
            color="gray"
            onClick={onClose}
          >
            <IconX size={18} />
          </ActionIcon>
        </Group>

        {/* Content */}
        <ScrollArea style={{ flex: 1 }}>
          <Box p="md">
            <form onSubmit={form.onSubmit(handleSubmit)}>
              <Stack gap="md">
                <Select
                  label="Application"
                  placeholder="Select an application"
                  required
                  data={applications.map(app => ({
                    value: app.app_id,
                    label: `${app.app_id} (${app.type.join(', ')})`,
                  }))}
                  {...form.getInputProps('app_id')}
                />

                <div>
                  <Text size="sm" fw={500} mb="xs">
                    Required Permissions
                  </Text>
                  <Text size="xs" c="dimmed" mb="md">
                    Select the permissions this token should have
                  </Text>
                  <PermissionTree
                    permissions={form.values.permissions}
                    onChange={(permissions) => form.setFieldValue('permissions', permissions)}
                  />
                </div>

                <TextInput
                  label="Owner Name"
                  placeholder="Token owner name"
                  {...form.getInputProps('owner.name')}
                />

                <TextInput
                  label="Owner Email"
                  placeholder="owner@example.com"
                  {...form.getInputProps('owner.owner')}
                />

                <Group justify="flex-end" mt="md">
                  <Button
                    variant="light"
                    onClick={onClose}
                  >
                    Cancel
                  </Button>
                  <Button 
                    type="submit"
                    disabled={applications.length === 0}
                  >
                    Create Token
                  </Button>
                </Group>
              </Stack>
            </form>
          </Box>
        </ScrollArea>
      </Paper>

      {/* Token Created Modal */}
      <Modal
        opened={tokenModalOpen}
        onClose={handleTokenModalClose}
        title="Token Created Successfully"
        size="lg"
        closeOnEscape={false}
        closeOnClickOutside={false}
      >
        <Stack gap="md">
          <Alert
            icon={<IconCheck size={16} />}
            title="Success!"
            color="green"
          >
            Your token has been created successfully. Please copy and store it securely as you won't be able to see it again.
          </Alert>

          <div>
            <Text size="sm" fw={500} mb="xs">
              Token:
            </Text>
            <Group gap="xs">
              <Code
                block
                style={{
                  flex: 1,
                  wordBreak: 'break-all',
                  whiteSpace: 'pre-wrap',
                }}
              >
                {createdToken?.token}
              </Code>
              <ActionIcon
                variant="light"
                onClick={() => createdToken?.token && copyToClipboard(createdToken.token)}
                title="Copy Token"
              >
                <IconCopy size={16} />
              </ActionIcon>
            </Group>
          </div>

          {createdToken?.prefix && (
            <div>
              <Text size="sm" fw={500} mb="xs">
                Token Prefix:
              </Text>
              <Code>{createdToken.prefix}</Code>
            </div>
          )}

          <Divider />

          <div>
            <Text size="sm" fw={500} mb="xs">
              Token Details:
            </Text>
            <Stack gap="xs">
              <Group justify="space-between">
                <Text size="sm">Token ID:</Text>
                <Code>{createdToken?.id}</Code>
              </Group>
              <Group justify="space-between">
                <Text size="sm">Type:</Text>
                <Code>{createdToken?.type}</Code>
              </Group>
              {createdToken?.permissions && (
                <div>
                  <Text size="sm" mb="xs">Permissions:</Text>
                  <Group gap="xs">
                    {createdToken.permissions.map((permission) => (
                      <Code key={permission} size="xs">
                        {permission}
                      </Code>
                    ))}
                  </Group>
                </div>
              )}
            </Stack>
          </div>

          <Group justify="flex-end" mt="md">
            <Button onClick={handleTokenModalClose}>
              Done
            </Button>
          </Group>
        </Stack>
      </Modal>
    </>
  );
};

export default TokenSidebar;