import express from 'express';
import Project from '../models/Project.js';
import AIChat from '../models/AIChat.js';
import { authenticateToken } from '../middleware/auth.js';

const router = express.Router();

// Mock AI responses for MVP
const MOCK_AI_RESPONSES = {
  'code': `import React from 'react';

export const GeneratedComponent = ({ title, children }) => (
  <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-200">
    <h2 className="text-lg font-bold text-blue-900 mb-2">{title || 'Component'}</h2>
    <div className="text-gray-700">{children}</div>
  </div>
);`,
  'analysis': 'Based on the design system analysis, this component uses semantic colors from the design tokens. Recommended: Implement responsive padding and ensure accessibility with proper ARIA labels.',
  'navigation': { type: 'hierarchical', structure: ['Home', 'Components', 'Tokens', 'Settings'], metadata: { depth: 2, itemCount: 4 } }
};

// 1. POST /api/claude/chat - Chat with Claude for design help
router.post('/claude/chat', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, message, context } = req.body;

    if (!message) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Message is required',
        data: null
      });
    }

    // Verify project ownership if provided
    if (projectId) {
      const project = await Project.findOne({
        where: { id: projectId, userId: req.user.id }
      });
      if (!project) {
        return res.status(404).json({
          status: 'error',
          code: 'PROJECT_NOT_FOUND',
          message: 'Project not found',
          data: null
        });
      }
    }

    const aiChat = await AIChat.create({
      projectId: projectId || null,
      userId: req.user.id,
      messageType: 'claude-query',
      status: 'processing',
      userMessage: message,
      metadata: { context: context || {}, provider: 'claude' }
    });

    // Mock Claude API response
    setTimeout(async () => {
      try {
        const response = MOCK_AI_RESPONSES.analysis;
        await aiChat.update({
          aiResponse: response,
          status: 'completed',
          inputTokens: Math.ceil(message.length / 4),
          outputTokens: Math.ceil(response.length / 4),
          completedAt: new Date()
        });
      } catch (error) {
        console.error('[AI] Error updating chat:', error);
      }
    }, 1000);

    console.log(`[AI] Claude chat started: ${aiChat.id}`);

    res.status(202).json({
      status: 'success',
      code: 'CLAUDE_CHAT_STARTED',
      message: 'Chat session started with Claude',
      data: {
        chatId: aiChat.id,
        sessionId: aiChat.sessionId,
        status: 'processing',
        estimatedTime: '2-5 seconds'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 2. POST /api/ai/chat - Generic AI chat
router.post('/chat', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, message, context } = req.body;

    if (!message) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Message is required',
        data: null
      });
    }

    if (projectId) {
      const project = await Project.findOne({
        where: { id: projectId, userId: req.user.id }
      });
      if (!project) {
        return res.status(404).json({
          status: 'error',
          code: 'PROJECT_NOT_FOUND',
          message: 'Project not found',
          data: null
        });
      }
    }

    const aiChat = await AIChat.create({
      projectId: projectId || null,
      userId: req.user.id,
      messageType: 'ai-query',
      status: 'processing',
      userMessage: message,
      metadata: { context: context || {}, provider: 'generic-ai' }
    });

    setTimeout(async () => {
      try {
        const response = MOCK_AI_RESPONSES.analysis;
        await aiChat.update({
          aiResponse: response,
          status: 'completed',
          inputTokens: Math.ceil(message.length / 4),
          outputTokens: Math.ceil(response.length / 4),
          completedAt: new Date()
        });
      } catch (error) {
        console.error('[AI] Error updating chat:', error);
      }
    }, 1200);

    console.log(`[AI] Generic AI chat started: ${aiChat.id}`);

    res.status(202).json({
      status: 'success',
      code: 'AI_CHAT_STARTED',
      message: 'AI chat session started',
      data: {
        chatId: aiChat.id,
        sessionId: aiChat.sessionId,
        status: 'processing',
        estimatedTime: '2-5 seconds'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 3. POST /api/dss/save-tokens - Save design tokens to DSS
router.post('/save-tokens', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, tokens, tokenName } = req.body;

    if (!projectId || !tokens || !tokenName) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'projectId, tokens, and tokenName are required',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(404).json({
        status: 'error',
        code: 'PROJECT_NOT_FOUND',
        message: 'Project not found',
        data: null
      });
    }

    const aiChat = await AIChat.create({
      projectId,
      userId: req.user.id,
      messageType: 'token-save',
      status: 'processing',
      userMessage: `Saving tokens: ${tokenName}`,
      tokens: tokens,
      metadata: { tokenName, tokenCount: Object.keys(tokens).length }
    });

    setTimeout(async () => {
      try {
        await aiChat.update({
          status: 'completed',
          completedAt: new Date()
        });
      } catch (error) {
        console.error('[AI] Error saving tokens:', error);
      }
    }, 800);

    console.log(`[AI] Tokens saved: ${aiChat.id}`);

    res.status(202).json({
      status: 'success',
      code: 'TOKENS_SAVED',
      message: 'Design tokens saved to DSS',
      data: {
        sessionId: aiChat.sessionId,
        tokenName,
        tokenCount: Object.keys(tokens).length,
        estimatedTime: '1-2 seconds'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 4. POST /api/navigation/generate - Generate navigation structures
router.post('/generate', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, componentList, depth = 2 } = req.body;

    if (!projectId || !componentList || !Array.isArray(componentList)) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'projectId and componentList (array) are required',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(404).json({
        status: 'error',
        code: 'PROJECT_NOT_FOUND',
        message: 'Project not found',
        data: null
      });
    }

    const navigationStructure = {
      type: 'hierarchical',
      depth,
      items: componentList,
      structure: ['Overview', ...componentList, 'Settings'],
      generatedAt: new Date().toISOString()
    };

    const aiChat = await AIChat.create({
      projectId,
      userId: req.user.id,
      messageType: 'navigation-gen',
      status: 'processing',
      userMessage: `Generate navigation for components: ${componentList.join(', ')}`,
      navigationStructure,
      metadata: { componentCount: componentList.length, depth }
    });

    setTimeout(async () => {
      try {
        await aiChat.update({
          status: 'completed',
          completedAt: new Date()
        });
      } catch (error) {
        console.error('[AI] Error generating navigation:', error);
      }
    }, 600);

    console.log(`[AI] Navigation generated: ${aiChat.id}`);

    res.status(202).json({
      status: 'success',
      code: 'NAVIGATION_GENERATED',
      message: 'Navigation structure generated',
      data: {
        sessionId: aiChat.sessionId,
        structure: navigationStructure.structure,
        itemCount: navigationStructure.structure.length,
        estimatedTime: '1 second'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 5. POST /api/system/reset - Admin system reset
router.post('/reset', authenticateToken, async (req, res, next) => {
  try {
    const { confirmReset } = req.body;

    if (confirmReset !== true) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'confirmReset must be true to proceed',
        data: null
      });
    }

    // Log the reset attempt
    const aiChat = await AIChat.create({
      userId: req.user.id,
      messageType: 'claude-query',
      status: 'completed',
      userMessage: 'System reset initiated',
      aiResponse: 'System reset operation logged',
      metadata: { operation: 'system-reset', timestamp: new Date().toISOString() }
    });

    console.log(`[System] Reset initiated by user: ${req.user.id}`);

    res.status(200).json({
      status: 'success',
      code: 'SYSTEM_RESET_INITIATED',
      message: 'System reset initiated (mock)',
      data: {
        resetTime: new Date().toISOString(),
        status: 'logged'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 6. GET /api/assets/list - List design assets
router.get('/assets-list', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, limit = 20, offset = 0 } = req.query;

    const maxLimit = 100;
    const queryLimit = Math.min(parseInt(limit) || 20, maxLimit);
    const queryOffset = parseInt(offset) || 0;

    if (!projectId) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'projectId is required',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(404).json({
        status: 'error',
        code: 'PROJECT_NOT_FOUND',
        message: 'Project not found',
        data: null
      });
    }

    // Mock asset list
    const mockAssets = [
      { id: '1', name: 'Button.svg', type: 'component', size: 2048, createdAt: new Date().toISOString() },
      { id: '2', name: 'Input.svg', type: 'component', size: 1536, createdAt: new Date().toISOString() },
      { id: '3', name: 'Card.svg', type: 'component', size: 3072, createdAt: new Date().toISOString() },
      { id: '4', name: 'Colors.json', type: 'token', size: 512, createdAt: new Date().toISOString() },
      { id: '5', name: 'Typography.json', type: 'token', size: 768, createdAt: new Date().toISOString() }
    ];

    const paginatedAssets = mockAssets.slice(queryOffset, queryOffset + queryLimit);

    res.status(200).json({
      status: 'success',
      code: 'ASSETS_RETRIEVED',
      message: 'Design assets retrieved successfully',
      data: {
        assets: paginatedAssets,
        pagination: {
          total: mockAssets.length,
          limit: queryLimit,
          offset: queryOffset
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/ai/chat/:id - Get chat history and status
router.get('/:id', authenticateToken, async (req, res, next) => {
  try {
    const aiChat = await AIChat.findOne({
      where: { id: req.params.id, userId: req.user.id }
    });

    if (!aiChat) {
      return res.status(404).json({
        status: 'error',
        code: 'CHAT_NOT_FOUND',
        message: 'Chat session not found',
        data: null
      });
    }

    res.status(200).json({
      status: 'success',
      code: 'CHAT_RETRIEVED',
      message: 'Chat session retrieved successfully',
      data: {
        chat: {
          id: aiChat.id,
          sessionId: aiChat.sessionId,
          messageType: aiChat.messageType,
          status: aiChat.status,
          userMessage: aiChat.userMessage,
          aiResponse: aiChat.aiResponse,
          generatedCode: aiChat.generatedCode,
          navigationStructure: aiChat.navigationStructure,
          inputTokens: aiChat.inputTokens,
          outputTokens: aiChat.outputTokens,
          model: aiChat.model,
          completedAt: aiChat.completedAt,
          createdAt: aiChat.createdAt
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/ai/sessions - List user chat sessions
router.get('/sessions/list', authenticateToken, async (req, res, next) => {
  try {
    const { limit = 20, offset = 0 } = req.query;

    const maxLimit = 100;
    const queryLimit = Math.min(parseInt(limit) || 20, maxLimit);
    const queryOffset = parseInt(offset) || 0;

    const { count, rows } = await AIChat.findAndCountAll({
      where: { userId: req.user.id },
      limit: queryLimit,
      offset: queryOffset,
      order: [['createdAt', 'DESC']],
      attributes: ['id', 'sessionId', 'messageType', 'status', 'userMessage', 'createdAt']
    });

    res.status(200).json({
      status: 'success',
      code: 'SESSIONS_RETRIEVED',
      message: 'Chat sessions retrieved successfully',
      data: {
        sessions: rows,
        pagination: {
          total: count,
          limit: queryLimit,
          offset: queryOffset
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
