import React from 'react';
import {
  Box,
  VStack,
  HStack,
  Grid,
  Flex,
  Text,
  Button,
  Icon,
  Badge,
  Divider,
  useColorModeValue,
  Card,
  CardHeader,
  CardBody,
  CardFooter,
  Progress,
  List,
  ListItem,
  IconButton,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  Tooltip,
  useDisclosure,
  Link,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Spinner,
  useToast,
  Stack,
  Heading,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Checkbox,
  Input,
  Select,
  ButtonGroup
} from '@chakra-ui/react';
import {
  FiZap,
  FiRefreshCw,
  FiExternalLink,
  FiCheck,
  FiAlertTriangle,
  FiBox,
  FiShoppingBag,
  FiTruck,
  FiPlus,
  FiEdit2,
  FiTrash2,
  FiMoreVertical,
  FiClock,
  FiActivity,
  FiAlertCircle,
  FiPower,
  FiServer,
  FiShield,
  FiGlobe,
} from 'react-icons/fi';
import ConnectionWizard from '../common/ConnectionWizard';

// Kaufland theme colors
const theme = {
  primary: '#E10915',    // Kaufland Red
  secondary: '#003C82',  // Dark Blue
  accent: '#0059C4',     // Light Blue
  gray: '#757575'
};

const StatusHero = ({ isConnected, onTest, onManage }) => (
  <Box
    bg={useColorModeValue('white', 'gray.800')}
    rounded="xl"
    p={6}
    position="relative"
    overflow="hidden"
    borderWidth={2}
    borderColor={isConnected ? 'green.100' : 'red.100'}
  >
    {/* Background Pattern */}
    <Box
      position="absolute"
      top={0}
      right={0}
      w="40%"
      h="100%"
      bg={`linear-gradient(45deg, transparent 0%, ${isConnected ? 'green.50' : 'red.50'} 100%)`}
      opacity={0.5}
    />

    <VStack align="stretch" spacing={4}>
      <Flex justify="space-between" align="center">
        <HStack>
          <Icon
            as={FiZap}
            color={isConnected ? 'green.500' : theme.primary}
            boxSize={6}
          />
          <Text fontSize="2xl" fontWeight="bold">
            {isConnected ? 'Connected to Kaufland DE' : 'Not Connected'}
          </Text>
        </HStack>
        <Badge
          colorScheme={isConnected ? 'green' : 'red'}
          fontSize="md"
          px={3}
          py={1}
          rounded="full"
        >
          {isConnected ? 'ACTIVE' : 'INACTIVE'}
        </Badge>
      </Flex>

      <Grid templateColumns="repeat(3, 1fr)" gap={6}>
        <GridItem>
          <VStack align="start" spacing={1}>
            <Text color="gray.500" fontSize="sm">Last Sync</Text>
            <Text fontWeight="medium">2 minutes ago</Text>
          </VStack>
        </GridItem>
        <GridItem>
          <VStack align="start" spacing={1}>
            <Text color="gray.500" fontSize="sm">API Health</Text>
            <HStack>
              <Icon as={FiCheck} color="green.500" />
              <Text fontWeight="medium">98% Uptime</Text>
            </HStack>
          </VStack>
        </GridItem>
        <GridItem>
          <VStack align="start" spacing={1}>
            <Text color="gray.500" fontSize="sm">Products Synced</Text>
            <Text fontWeight="medium">156 Products</Text>
          </VStack>
        </GridItem>
      </Grid>

      <HStack spacing={4}>
        <Button
          leftIcon={<FiRefreshCw />}
          onClick={onTest}
          variant="outline"
          colorScheme={isConnected ? 'green' : 'red'}
        >
          Test Connection
        </Button>
        <Button
          colorScheme="blue"
          onClick={onManage}
        >
          Manage Connection
        </Button>
      </HStack>
    </VStack>
  </Box>
);

const QuickAction = ({ icon, title, subtitle, onClick }) => (
  <Card
    variant="outline"
    cursor="pointer"
    transition="all 0.2s"
    _hover={{ transform: 'translateY(-2px)', shadow: 'md' }}
    onClick={onClick}
  >
    <CardBody>
      <VStack spacing={3}>
        <Icon as={icon} boxSize={6} color={theme.accent} />
        <VStack spacing={1}>
          <Text fontWeight="medium">{title}</Text>
          <Text fontSize="sm" color="gray.500">{subtitle}</Text>
        </VStack>
      </VStack>
    </CardBody>
  </Card>
);

const ConnectionCard = ({ connection, onEdit, onTest, onDelete }) => (
  <Card variant="outline" mb={4}>
    <CardBody>
      <Flex justify="space-between" align="start">
        <VStack align="start" spacing={2}>
          <HStack>
            <Text fontSize="lg" fontWeight="bold">{connection.marketplace}</Text>
            <Badge colorScheme="green">Connected</Badge>
          </HStack>

          <Grid templateColumns="repeat(2, 1fr)" gap={4}>
            <VStack align="start" spacing={0}>
              <Text fontSize="sm" color="gray.500">Client ID</Text>
              <Text fontSize="sm" fontWeight="medium">****{connection.clientId.slice(-4)}</Text>
            </VStack>
            <VStack align="start" spacing={0}>
              <Text fontSize="sm" color="gray.500">Connected Since</Text>
              <Text fontSize="sm" fontWeight="medium">{connection.connectedSince}</Text>
            </VStack>
          </Grid>
        </VStack>

        <Menu>
          <MenuButton
            as={IconButton}
            icon={<FiMoreVertical />}
            variant="ghost"
            size="sm"
          />
          <MenuList>
            <MenuItem icon={<FiEdit2 />} onClick={onEdit}>Edit</MenuItem>
            <MenuItem icon={<FiRefreshCw />} onClick={onTest}>Test</MenuItem>
            <MenuItem icon={<FiTrash2 />} onClick={onDelete} color="red.500">Delete</MenuItem>
          </MenuList>
        </Menu>
      </Flex>
    </CardBody>
  </Card>
);

const MetricCard = ({ icon, title, value, subtitle, onClick }) => (
  <Card variant="outline">
    <CardBody>
      <VStack spacing={2}>
        <Icon as={icon} boxSize={5} color={theme.accent} />
        <VStack spacing={0}>
          <Text fontSize="2xl" fontWeight="bold">{value}</Text>
          <Text fontSize="sm" color="gray.500">{title}</Text>
        </VStack>
        {subtitle && (
          <Text fontSize="xs" color="gray.500">{subtitle}</Text>
        )}
      </VStack>
    </CardBody>
    <CardFooter pt={0}>
      <Button size="sm" variant="ghost" width="full" onClick={onClick}>
        View Details
      </Button>
    </CardFooter>
  </Card>
);

const ActivityItem = ({ icon, title, time, status }) => (
  <ListItem py={2}>
    <HStack spacing={3}>
      <Icon as={icon} color={status === 'success' ? 'green.500' : 'gray.500'} />
      <VStack spacing={0} align="start" flex={1}>
        <Text fontSize="sm" fontWeight="medium">{title}</Text>
        <Text fontSize="xs" color="gray.500">{time}</Text>
      </VStack>
      {status === 'success' && <Icon as={FiCheck} color="green.500" />}
    </HStack>
  </ListItem>
);

const ConnectionStatus = ({
  isConnected,
  connection,
  onConnect,
  onTest,
  onEdit,
  onDisconnect,
  isLoading
}) => (
  <Card
    variant="outline"
    borderWidth={2}
    borderColor={isConnected ? 'green.100' : 'red.50'}
    bg={useColorModeValue('white', 'gray.800')}
    position="relative"
    overflow="hidden"
  >
    {/* Background Pattern */}
    <Box
      position="absolute"
      top={0}
      right={0}
      width="50%"
      height="100%"
      bg={`linear-gradient(135deg,
        ${isConnected ? 'rgba(49, 151, 149, 0.06)' : 'rgba(225, 9, 21, 0.06)'} 0%,
        transparent 100%)`}
      borderLeftRadius="full"
    />

    <CardBody p={8}>
      <VStack align="stretch" spacing={6}>
        {/* Status Header */}
        <Flex justify="space-between" align="center">
          <HStack spacing={4}>
            <Box
              p={2}
              bg={isConnected ? 'green.50' : 'red.50'}
              rounded="full"
              transition="all 0.2s"
            >
              <Icon
                as={isConnected ? FiCheck : FiAlertCircle}
                color={isConnected ? 'green.500' : theme.primary}
                boxSize={6}
              />
            </Box>
            <VStack align="start" spacing={0}>
              <Text fontSize="2xl" fontWeight="bold" color={theme.secondary}>
                Kaufland API
              </Text>
              <Text fontSize="sm" color="gray.500">
                {isConnected ? 'Connected and ready' : 'Not connected'}
              </Text>
            </VStack>
          </HStack>
          <Badge
            colorScheme={isConnected ? 'green' : 'red'}
            fontSize="md"
            px={4}
            py={2}
            rounded="full"
            textTransform="none"
            fontWeight="medium"
          >
            {isConnected ? 'Active' : 'Inactive'}
          </Badge>
        </Flex>

        <Divider />

        {/* Connection Details or Connect Button */}
        {isConnected && connection ? (
          <VStack align="stretch" spacing={6}>
            {/* Connection Info */}
            <Grid templateColumns="repeat(2, 1fr)" gap={8}>
              <Box>
                <HStack spacing={3} mb={2}>
                  <Icon as={FiShield} color="gray.400" />
                  <Text fontSize="sm" color="gray.500">Client ID</Text>
                </HStack>
                <Text fontSize="lg" fontWeight="semibold">
                  ****{connection.clientId.slice(-4)}
                </Text>
              </Box>
              <Box>
                <HStack spacing={3} mb={2}>
                  <Icon as={FiClock} color="gray.400" />
                  <Text fontSize="sm" color="gray.500">Connected Since</Text>
                </HStack>
                <Text fontSize="lg" fontWeight="semibold">
                  {new Date(connection.connectedSince).toLocaleDateString()}
                </Text>
              </Box>
            </Grid>

            {/* Action Buttons */}
            <HStack spacing={4}>
              <Button
                leftIcon={isLoading ? <Spinner size="sm" /> : <FiRefreshCw />}
                onClick={onTest}
                colorScheme="blue"
                flex={1}
                isLoading={isLoading}
                size="lg"
                _hover={{
                  transform: 'translateY(-2px)',
                  shadow: 'lg',
                }}
                _active={{
                  transform: 'translateY(0)',
                  shadow: 'md',
                }}
                transition="all 0.2s"
              >
                Test Connection
              </Button>
              <Button
                leftIcon={<FiEdit2 />}
                onClick={onEdit}
                variant="outline"
                flex={1}
                size="lg"
                _hover={{
                  transform: 'translateY(-2px)',
                  shadow: 'md',
                  bg: 'gray.50',
                }}
                _active={{
                  transform: 'translateY(0)',
                  shadow: 'sm',
                }}
                transition="all 0.2s"
              >
                Edit Credentials
              </Button>
              <Button
                leftIcon={<FiPower />}
                onClick={onDisconnect}
                colorScheme="red"
                variant="ghost"
                flex={1}
                size="lg"
                _hover={{
                  bg: 'red.50',
                  transform: 'translateY(-2px)',
                  shadow: 'sm',
                }}
                _active={{
                  transform: 'translateY(0)',
                }}
                transition="all 0.2s"
              >
                Disconnect
              </Button>
            </HStack>
          </VStack>
        ) : (
          <VStack spacing={8} py={6}>
            <VStack spacing={2}>
              <Text
                fontSize="lg"
                fontWeight="medium"
                color="gray.600"
                textAlign="center"
                maxW="md"
              >
                Connect your WooCommerce store to the Kaufland marketplace
                to start selling.
              </Text>
              <Text fontSize="sm" color="gray.500" textAlign="center">
                You'll need your Kaufland API credentials to proceed.
              </Text>
            </VStack>
            <Button
              leftIcon={<FiZap />}
              onClick={onConnect}
              colorScheme="blue"
              size="lg"
              width="full"
              maxW="md"
              h="56px"
              fontSize="md"
              _hover={{
                transform: 'translateY(-2px)',
                shadow: 'lg',
              }}
              _active={{
                transform: 'translateY(-1px)',
                shadow: 'md',
              }}
              transition="all 0.2s"
            >
              Connect to Kaufland
            </Button>
          </VStack>
        )}
      </VStack>
    </CardBody>
  </Card>
);

const TestResultsModal = ({ isOpen, onClose, results }) => (
  <Modal isOpen={isOpen} onClose={onClose} size="md">
    <ModalOverlay />
    <ModalContent>
      <ModalHeader>Connection Test Results</ModalHeader>
      <ModalBody>
        <VStack spacing={6} align="stretch">
          {/* Overall Status */}
          <Box p={4} bg={results?.success ? 'green.50' : 'red.50'} rounded="md">
            <HStack>
              <Icon
                as={results?.success ? FiCheck : FiAlertCircle}
                color={results?.success ? 'green.500' : 'red.500'}
                boxSize={5}
              />
              <Text fontWeight="medium">
                {results?.success ? 'Connection Successful' : 'Connection Failed'}
              </Text>
            </HStack>
          </Box>

          {/* Detailed Checks */}
          <Box>
            <Text fontSize="sm" fontWeight="bold" mb={3}>Detailed Results:</Text>
            <List spacing={3}>
              <ListItem>
                <HStack>
                  <Icon as={FiServer} color="blue.500" />
                  <Box>
                    <Text fontWeight="medium">API Endpoint</Text>
                    <Text fontSize="sm" color="gray.500">
                      Successfully connected to Kaufland API
                    </Text>
                  </Box>
                  <Icon as={FiCheck} color="green.500" ml="auto" />
                </HStack>
              </ListItem>
              <ListItem>
                <HStack>
                  <Icon as={FiShield} color="blue.500" />
                  <Box>
                    <Text fontWeight="medium">Authentication</Text>
                    <Text fontSize="sm" color="gray.500">
                      API credentials validated
                    </Text>
                  </Box>
                  <Icon as={FiCheck} color="green.500" ml="auto" />
                </HStack>
              </ListItem>
              <ListItem>
                <HStack>
                  <Icon as={FiGlobe} color="blue.500" />
                  <Box>
                    <Text fontWeight="medium">Marketplace Access</Text>
                    <Text fontSize="sm" color="gray.500">
                      Required permissions granted
                    </Text>
                  </Box>
                  <Icon as={FiCheck} color="green.500" ml="auto" />
                </HStack>
              </ListItem>
            </List>
          </Box>
        </VStack>
      </ModalBody>
      <ModalFooter>
        <Button colorScheme="blue" onClick={onClose}>Close</Button>
      </ModalFooter>
    </ModalContent>
  </Modal>
);

const ConnectionHistory = ({ history }) => (
  <Card variant="outline">
    <CardHeader>
      <Text fontSize="lg" fontWeight="bold">Connection History</Text>
    </CardHeader>
    <CardBody>
      <List spacing={3}>
        {history.map((item, index) => (
          <ListItem key={index}>
            <HStack spacing={3}>
              <Icon
                as={item.icon}
                color={item.status === 'success' ? 'green.500' : 'gray.500'}
              />
              <VStack spacing={0} align="start" flex={1}>
                <Text fontSize="sm" fontWeight="medium">
                  {item.title}
                </Text>
                <Text fontSize="xs" color="gray.500">
                  {item.time}
                </Text>
              </VStack>
              {item.status === 'success' && (
                <Icon as={FiCheck} color="green.500" />
              )}
            </HStack>
          </ListItem>
        ))}
      </List>
    </CardBody>
  </Card>
);

const Dashboard = () => {
  const { isOpen: isWizardOpen, onOpen: onWizardOpen, onClose: onWizardClose } = useDisclosure();
  const { isOpen: isTestResultsOpen, onOpen: onTestResultsOpen, onClose: onTestResultsClose } = useDisclosure();
  const [connectionState, setConnectionState] = React.useState({
    isConnected: false,
    isLoading: false,
    details: null,
    lastTest: null,
    error: null
  });
  const toast = useToast();

  // Fetch connection status on mount
  React.useEffect(() => {
    fetchConnectionStatus();
  }, []);

  const fetchConnectionStatus = async () => {
    try {
      setConnectionState(prev => ({ ...prev, isLoading: true }));

      const response = await fetch('/wp-json/klcnn/v1/connection', {
        method: 'GET',
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      const data = await response.json();

      if (data.success && data.data) {
        setConnectionState(prev => ({
          ...prev,
          isConnected: true,
          isLoading: false,
          details: {
            clientId: data.data.clientId,
            connectedSince: data.data.connectedSince,
          }
        }));
      } else {
        setConnectionState(prev => ({
          ...prev,
          isConnected: false,
          isLoading: false,
          details: null
        }));
      }
    } catch (error) {
      console.error('Error fetching connection status:', error);
      setConnectionState(prev => ({
        ...prev,
        isConnected: false,
        isLoading: false,
        error: error.message
      }));
    }
  };

  const handleConnect = () => {
    onWizardOpen();
  };

  const handleTest = async () => {
    setConnectionState(prev => ({ ...prev, isLoading: true }));

    try {
      // First get the current connection details
      const response = await fetch('/wp-json/klcnn/v1/categories', {
        method: 'POST',
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          clientKey: connectionState.details.clientId,
          secretKey: await getCurrentSecretKey(),
          marketplace: 'de'  // Or get from connection details if stored
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Connection test failed');
      }

      setConnectionState(prev => ({
        ...prev,
        isLoading: false,
        lastTest: {
          date: new Date().toLocaleString(),
          success: true,
          message: data.message || 'Connection test successful',
          details: data.data
        }
      }));

      onTestResultsOpen();

      toast({
        title: "Connection Test Successful",
        description: "Successfully connected to Kaufland API",
        status: "success",
        duration: 5000,
        isClosable: true,
      });
    } catch (error) {
      console.error('Test connection error:', error);
      setConnectionState(prev => ({
        ...prev,
        isLoading: false,
        lastTest: {
          date: new Date().toLocaleString(),
          success: false,
          message: error.message
        }
      }));

      toast({
        title: "Connection Test Failed",
        description: error.message,
        status: "error",
        duration: 5000,
        isClosable: true,
      });
    }
  };

  // Helper function to get the current secret key
  const getCurrentSecretKey = async () => {
    try {
      const response = await fetch('/wp-json/klcnn/v1/connection/secret', {
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error('Failed to retrieve connection details');
      }

      return data.secretKey;
    } catch (error) {
      throw new Error('Failed to retrieve connection details: ' + error.message);
    }
  };

  const handleEdit = () => {
    onWizardOpen();
  };

  const handleDisconnect = async () => {
    try {
      setConnectionState(prev => ({ ...prev, isLoading: true }));

      const response = await fetch('/wp-json/klcnn/v1/connection', {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce
        }
      });

      const data = await response.json();

      if (data.success) {
        setConnectionState(prev => ({
          ...prev,
          isConnected: false,
          isLoading: false,
          details: null,
          lastTest: null
        }));

        toast({
          title: "Disconnected",
          description: "Successfully disconnected from Kaufland API",
          status: "info",
          duration: 5000,
          isClosable: true,
        });
      } else {
        throw new Error(data.message || 'Failed to disconnect');
      }
    } catch (error) {
      setConnectionState(prev => ({
        ...prev,
        isLoading: false,
        error: error.message
      }));

      toast({
        title: "Error",
        description: error.message,
        status: "error",
        duration: 5000,
        isClosable: true,
      });
    }
  };

  const handleSaveConnection = async (credentials) => {
    try {
      setConnectionState(prev => ({ ...prev, isLoading: true }));

      const response = await fetch('/wp-json/klcnn/v1/connection', {
        method: 'POST',
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      });

      const data = await response.json();

      if (data.success) {
        setConnectionState(prev => ({
          ...prev,
          isConnected: true,
          isLoading: false,
          details: {
            clientId: credentials.clientId,
            connectedSince: new Date().toISOString(),
          }
        }));

        toast({
          title: "Connected",
          description: "Successfully connected to Kaufland API",
          status: "success",
          duration: 5000,
          isClosable: true,
        });

        onWizardClose();
      } else {
        throw new Error(data.message || 'Failed to save connection');
      }
    } catch (error) {
      setConnectionState(prev => ({
        ...prev,
        isLoading: false,
        error: error.message
      }));

      toast({
        title: "Error",
        description: error.message,
        status: "error",
        duration: 5000,
        isClosable: true,
      });
    }
  };

  return (
    <VStack spacing={6} align="stretch" maxW="container.lg" mx="auto">
      <ConnectionStatus
        isConnected={connectionState.isConnected}
        connection={connectionState.details}
        onConnect={handleConnect}
        onTest={handleTest}
        onEdit={handleEdit}
        onDisconnect={handleDisconnect}
        isLoading={connectionState.isLoading}
      />

      <ConnectionHistory history={[]} />

      <ConnectionWizard
        isOpen={isWizardOpen}
        onClose={onWizardClose}
        onSave={handleSaveConnection}
      />

      <TestResultsModal
        isOpen={isTestResultsOpen}
        onClose={onTestResultsClose}
        results={connectionState.lastTest}
      />
    </VStack>
  );
};

export default Dashboard;