/**
 * DevDocsPage - Admin Documentation Viewer
 * 
 * REQUIRED DEPENDENCIES:
 * npm install react-markdown react-syntax-highlighter
 * npm install --save-dev @types/react-syntax-highlighter
 * 
 * This component requires these packages to render markdown with syntax highlighting.
 */

import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Heading,
  Text,
  VStack,
  HStack,
  Button,
  Input,
  InputGroup,
  InputLeftElement,
  Select,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  Badge,
  Icon,
  useColorModeValue,
  Divider,
  Code,
  Alert,
  AlertIcon,
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  Spinner,
  useToast,
} from '@chakra-ui/react';
import {
  FiSearch,
  FiBook,
  FiCode,
  FiFileText,
  FiLayers,
  FiTool,
  FiHome,
  FiDownload,
  FiRefreshCw,
} from 'react-icons/fi';
import { Link as RouterLink } from 'react-router-dom';

// @ts-ignore - Install with: npm install react-markdown
import ReactMarkdown from 'react-markdown';
// @ts-ignore - Install with: npm install react-syntax-highlighter
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
// @ts-ignore
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';

interface DocFile {
  name: string;
  path: string;
  category: string;
  description: string;
  icon: any;
  tags: string[];
}

const DevDocsPage: React.FC = () => {
  const [selectedDoc, setSelectedDoc] = useState<string>('');
  const [docContent, setDocContent] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [loading, setLoading] = useState(false);
  const toast = useToast();
  
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const sidebarBg = useColorModeValue('gray.50', 'gray.900');

  // Documentation files registry
  const docFiles: DocFile[] = [
    {
      name: 'MyUIbrix Elementor Features',
      path: '/DOCS/MYUIBRIX_ELEMENTOR_FEATURES.md',
      category: 'Features',
      description: 'Complete guide to Elementor-style page builder features',
      icon: FiLayers,
      tags: ['myuibrix', 'elementor', 'editor', 'features'],
    },
    {
      name: 'MyUIbrix Enhancement Summary',
      path: '/DOCS/MYUIBRIX_ENHANCEMENT_SUMMARY.md',
      category: 'Features',
      description: 'Implementation summary of Elementor enhancements',
      icon: FiTool,
      tags: ['myuibrix', 'enhancement', 'summary'],
    },
    {
      name: 'MyUIbrix Quick Start',
      path: '/DOCS/MYUIBRIX_QUICK_START.md',
      category: 'Guides',
      description: 'Quick reference guide for MyUIbrix editor',
      icon: FiBook,
      tags: ['myuibrix', 'quick-start', 'guide'],
    },
    {
      name: 'MyUIbrix Fixes',
      path: '/DOCS/MYUIBRIX_FIXES.md',
      category: 'Technical',
      description: 'Technical fixes and improvements documentation',
      icon: FiTool,
      tags: ['myuibrix', 'fixes', 'technical'],
    },
    {
      name: 'Integration Guide',
      path: '/DOCS/INTEGRATION_GUIDE.md',
      category: 'Development',
      description: 'How to integrate MyUIbrix components',
      icon: FiCode,
      tags: ['integration', 'development', 'components'],
    },
    {
      name: 'CSS Classes Reference',
      path: '/DOCS/CSS_CLASSES_REFERENCE.md',
      category: 'Reference',
      description: 'Complete CSS classes and selectors reference',
      icon: FiFileText,
      tags: ['css', 'styling', 'classes', 'reference'],
    },
    {
      name: 'Admin Functionality Report',
      path: '/DOCS/ADMIN_FUNCTIONALITY_REPORT.md',
      category: 'Admin',
      description: 'Complete admin panel functionality documentation',
      icon: FiTool,
      tags: ['admin', 'functionality', 'report'],
    },
    {
      name: 'Setup Improvements',
      path: '/DOCS/SETUP_IMPROVEMENTS.md',
      category: 'Setup',
      description: 'Initial setup and configuration guide',
      icon: FiBook,
      tags: ['setup', 'configuration', 'improvements'],
    },
    {
      name: 'Docker Enhancements',
      path: '/DOCS/DOCKER_ENHANCEMENTS_SUMMARY.md',
      category: 'DevOps',
      description: 'Docker setup and deployment guide',
      icon: FiCode,
      tags: ['docker', 'deployment', 'devops'],
    },
  ];

  const categories = ['all', 'Features', 'Guides', 'Technical', 'Development', 'Reference', 'Admin', 'Setup', 'DevOps'];

  // Filter documents
  const filteredDocs = docFiles.filter(doc => {
    const matchesSearch = searchQuery === '' || 
      doc.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      doc.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      doc.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()));
    
    const matchesCategory = selectedCategory === 'all' || doc.category === selectedCategory;
    
    return matchesSearch && matchesCategory;
  });

  // Load document content
  const loadDocument = async (docPath: string) => {
    setLoading(true);
    setSelectedDoc(docPath);
    
    try {
      // In production, fetch from backend API
      const response = await fetch(docPath);
      if (!response.ok) throw new Error('Failed to load document');
      
      const content = await response.text();
      setDocContent(content);
    } catch (error) {
      console.error('Error loading document:', error);
      
      // Fallback: show error message
      setDocContent(`# Document Not Found\n\nThe requested documentation file could not be loaded.\n\n**Path**: ${docPath}\n\nPlease ensure the documentation files are properly deployed.`);
      
      toast({
        title: 'Error loading document',
        description: 'The documentation file could not be loaded',
        status: 'error',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  // Load first document on mount
  useEffect(() => {
    if (docFiles.length > 0) {
      loadDocument(docFiles[0].path);
    }
  }, []);

  // Custom markdown components
  const markdownComponents = {
    code({ node, inline, className, children, ...props }: any) {
      const match = /language-(\w+)/.exec(className || '');
      return !inline && match ? (
        <SyntaxHighlighter
          style={vscDarkPlus}
          language={match[1]}
          PreTag="div"
          {...props}
        >
          {String(children).replace(/\n$/, '')}
        </SyntaxHighlighter>
      ) : (
        <Code {...props}>{children}</Code>
      );
    },
    h1: ({ children }: any) => (
      <Heading as="h1" size="2xl" mb={6} mt={8}>
        {children}
      </Heading>
    ),
    h2: ({ children }: any) => (
      <Heading as="h2" size="xl" mb={4} mt={6}>
        {children}
      </Heading>
    ),
    h3: ({ children }: any) => (
      <Heading as="h3" size="lg" mb={3} mt={5}>
        {children}
      </Heading>
    ),
    p: ({ children }: any) => (
      <Text mb={4} lineHeight="tall">
        {children}
      </Text>
    ),
    ul: ({ children }: any) => (
      <VStack as="ul" align="stretch" spacing={2} mb={4} pl={6}>
        {children}
      </VStack>
    ),
    li: ({ children }: any) => (
      <Text as="li" mb={1}>
        {children}
      </Text>
    ),
  };

  // Download document
  const downloadDocument = () => {
    const blob = new Blob([docContent], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = selectedDoc.split('/').pop() || 'document.md';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast({
      title: 'Document downloaded',
      status: 'success',
      duration: 2000,
    });
  };

  return (
    <Box minH="100vh" bg={useColorModeValue('gray.50', 'gray.900')}>
      {/* Breadcrumb */}
      <Box bg={bgColor} borderBottom="1px" borderColor={borderColor} py={4}>
        <Container maxW="container.xl">
          <Breadcrumb>
            <BreadcrumbItem>
              <BreadcrumbLink as={RouterLink} to="/admin">
                <HStack spacing={2}>
                  <FiHome />
                  <Text>Admin</Text>
                </HStack>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbItem isCurrentPage>
              <BreadcrumbLink>
                <HStack spacing={2}>
                  <FiBook />
                  <Text>Developer Documentation</Text>
                </HStack>
              </BreadcrumbLink>
            </BreadcrumbItem>
          </Breadcrumb>
        </Container>
      </Box>

      {/* Header */}
      <Box bg={bgColor} borderBottom="1px" borderColor={borderColor} py={6}>
        <Container maxW="container.xl">
          <VStack align="stretch" spacing={4}>
            <HStack justify="space-between" align="start">
              <VStack align="start" spacing={2}>
                <Heading size="lg">📚 Developer Documentation</Heading>
                <Text color="gray.600">
                  Complete technical documentation for MyUIbrix and admin features
                </Text>
              </VStack>
              <HStack spacing={2}>
                <Button
                  leftIcon={<FiDownload />}
                  size="sm"
                  variant="outline"
                  onClick={downloadDocument}
                  isDisabled={!selectedDoc}
                >
                  Download
                </Button>
                <Button
                  leftIcon={<FiRefreshCw />}
                  size="sm"
                  variant="outline"
                  onClick={() => selectedDoc && loadDocument(selectedDoc)}
                  isLoading={loading}
                >
                  Refresh
                </Button>
              </HStack>
            </HStack>

            {/* Search and Filter */}
            <HStack spacing={4}>
              <InputGroup maxW="400px">
                <InputLeftElement pointerEvents="none">
                  <FiSearch color="gray.300" />
                </InputLeftElement>
                <Input
                  placeholder="Search documentation..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  bg={bgColor}
                />
              </InputGroup>
              
              <Select
                maxW="200px"
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                bg={bgColor}
              >
                {categories.map(cat => (
                  <option key={cat} value={cat}>
                    {cat === 'all' ? 'All Categories' : cat}
                  </option>
                ))}
              </Select>
              
              <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                {filteredDocs.length} docs
              </Badge>
            </HStack>
          </VStack>
        </Container>
      </Box>

      {/* Main Content */}
      <Container maxW="container.xl" py={8}>
        <HStack align="start" spacing={6}>
          {/* Sidebar */}
          <VStack
            width="350px"
            bg={sidebarBg}
            borderRadius="lg"
            p={4}
            align="stretch"
            spacing={3}
            maxH="calc(100vh - 300px)"
            overflowY="auto"
            position="sticky"
            top="20px"
          >
            <Text fontWeight="bold" fontSize="sm" textTransform="uppercase" color="gray.500">
              Documentation Files
            </Text>
            
            {filteredDocs.length === 0 ? (
              <Alert status="info" borderRadius="md">
                <AlertIcon />
                No documents found
              </Alert>
            ) : (
              filteredDocs.map((doc) => (
                <Box
                  key={doc.path}
                  p={4}
                  bg={selectedDoc === doc.path ? 'blue.50' : bgColor}
                  borderRadius="md"
                  cursor="pointer"
                  transition="all 0.2s"
                  borderWidth="2px"
                  borderColor={selectedDoc === doc.path ? 'blue.400' : 'transparent'}
                  _hover={{
                    transform: 'translateX(4px)',
                    borderColor: 'blue.300',
                  }}
                  onClick={() => loadDocument(doc.path)}
                >
                  <HStack spacing={3} mb={2}>
                    <Icon as={doc.icon} boxSize={5} color="blue.500" />
                    <VStack align="start" spacing={0} flex={1}>
                      <Text fontWeight="bold" fontSize="sm">
                        {doc.name}
                      </Text>
                      <Badge colorScheme="purple" fontSize="xs">
                        {doc.category}
                      </Badge>
                    </VStack>
                  </HStack>
                  <Text fontSize="xs" color="gray.600">
                    {doc.description}
                  </Text>
                  <HStack spacing={1} mt={2} flexWrap="wrap">
                    {doc.tags.slice(0, 3).map(tag => (
                      <Badge key={tag} size="sm" variant="outline" fontSize="xs">
                        {tag}
                      </Badge>
                    ))}
                  </HStack>
                </Box>
              ))
            )}
          </VStack>

          {/* Content Area */}
          <Box
            flex={1}
            bg={bgColor}
            borderRadius="lg"
            p={8}
            boxShadow="sm"
            minH="600px"
          >
            {loading ? (
              <VStack spacing={4} py={12}>
                <Spinner size="xl" color="blue.500" />
                <Text color="gray.500">Loading documentation...</Text>
              </VStack>
            ) : docContent ? (
              <Box
                sx={{
                  '& pre': {
                    borderRadius: 'md',
                    marginBottom: '1rem',
                  },
                  '& table': {
                    width: '100%',
                    marginBottom: '1rem',
                    borderCollapse: 'collapse',
                  },
                  '& th': {
                    background: useColorModeValue('gray.100', 'gray.700'),
                    padding: '12px',
                    textAlign: 'left',
                    borderBottom: '2px solid',
                    borderColor: borderColor,
                  },
                  '& td': {
                    padding: '12px',
                    borderBottom: '1px solid',
                    borderColor: borderColor,
                  },
                  '& hr': {
                    margin: '2rem 0',
                    borderColor: borderColor,
                  },
                  '& blockquote': {
                    borderLeft: '4px solid',
                    borderColor: 'blue.400',
                    paddingLeft: '1rem',
                    marginLeft: 0,
                    fontStyle: 'italic',
                    color: 'gray.600',
                  },
                  '& img': {
                    maxWidth: '100%',
                    borderRadius: 'md',
                    boxShadow: 'md',
                    marginBottom: '1rem',
                  },
                }}
              >
                <ReactMarkdown components={markdownComponents}>
                  {docContent}
                </ReactMarkdown>
              </Box>
            ) : (
              <VStack spacing={4} py={12}>
                <Icon as={FiBook} boxSize={16} color="gray.300" />
                <Text color="gray.500">Select a document to view</Text>
              </VStack>
            )}
          </Box>
        </HStack>
      </Container>
    </Box>
  );
};

export default DevDocsPage;
