import { Controller, Get, Post, Body, Query, Param, NotFoundException, InternalServerErrorException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { ProductService } from '../services/product.service';
import { CustomerService } from '../services/customer.service';
import { EmailService } from '../services/email.service';
import { CmsService } from '../services/cms.service';
import { QuoteService } from '../services/quote.service';
import { TourService } from '../services/tour.service';

@ApiTags('Public')
@Controller('public')
export class PublicController {
  constructor(
    private readonly cmsService: CmsService,
    private readonly productService: ProductService,
    private readonly customerService: CustomerService,
    private readonly emailService: EmailService,
    private readonly quoteService: QuoteService,
    private readonly tourService: TourService,
  ) {}

  @Get('content/:section')
  @ApiOperation({ summary: 'Get CMS content for a specific section' })
  @ApiResponse({ status: 200, description: 'Returns CMS content for the section' })
  async getSectionContent(@Param('section') section: string) {
    return this.cmsService.getPublicPageContent(section);
  }

  @Get('content')
  @ApiOperation({ summary: 'Get all CMS content' })
  @ApiResponse({ status: 200, description: 'Returns all CMS content' })
  async getAllContent() {
    return this.cmsService.getAllContent();
  }

  @Get('theme')
  @ApiOperation({ summary: 'Get current theme configuration' })
  @ApiResponse({ status: 200, description: 'Returns theme configuration' })
  async getTheme() {
    return this.cmsService.getTheme();
  }

  @Get('products')
  @ApiOperation({ summary: 'Get public products for website display' })
  @ApiResponse({ status: 200, description: 'Returns public products' })
  async getPublicProducts(@Query() query: any) {
    // Get products that are marked as public/featured
    return this.productService.findPublicProducts(query);
  }

  @Get('products/featured')
  @ApiOperation({ summary: 'Get featured products' })
  @ApiResponse({ status: 200, description: 'Returns featured products' })
  async getFeaturedProducts() {
    return this.productService.findFeaturedProducts();
  }

  @Get('products/categories')
  @ApiOperation({ summary: 'Get product categories' })
  @ApiResponse({ status: 200, description: 'Returns product categories' })
  async getProductCategories() {
    return this.productService.getCategories();
  }

  @Get('products/:id')
  async getProductById(@Param('id') id: string) {
    try {
      const product = await this.productService.findOne(id);
      if (!product) {
        throw new NotFoundException('Product not found');
      }
      return product;
    } catch (error) {
      throw new InternalServerErrorException('Failed to fetch product');
    }
  }

  @Get('company/info')
  @ApiOperation({ summary: 'Get company information' })
  @ApiResponse({ status: 200, description: 'Returns company information' })
  async getCompanyInfo() {
    return {
      name: 'Monio Manufacturing',
      description: 'Leading African manufacturing company specializing in premium textiles, smart furniture, and advanced metalworks.',
      founded: 2020,
      location: 'Nairobi, Kenya',
      mission: 'To revolutionize manufacturing through innovation and excellence',
      vision: 'To be the leading manufacturing company in Africa',
      values: [
        'Innovation',
        'Quality',
        'Sustainability',
        'Excellence',
        'Collaboration'
      ],
      services: [
        'Custom Textile Manufacturing',
        'Smart Furniture Production',
        'Precision Metalworks',
        'Supply Chain Solutions',
        'Quality Assurance Services',
        'Custom Manufacturing'
      ],
      contact: {
        phone: '+254 700 000 000',
        email: 'info@monio.com',
        address: 'Monio Headquarters, Nairobi, Kenya',
        website: 'https://monio.com'
      }
    };
  }

  @Get('services')
  @ApiOperation({ summary: 'Get company services' })
  @ApiResponse({ status: 200, description: 'Returns company services' })
  async getServices() {
    return [
      {
        id: 1,
        title: 'Custom Textile Manufacturing',
        description: 'Premium fabric production with sustainable materials and custom designs for fashion and industrial applications',
        category: 'Textiles',
        features: [
          'Custom fabric designs and patterns',
          'Sustainable and eco-friendly materials',
          'Advanced weaving and finishing techniques',
          'Quality assurance and testing',
          'Bulk production capabilities',
          'Fast turnaround times'
        ],
        icon: 'textile',
        image: '/assets/services/textiles.jpg'
      },
      {
        id: 2,
        title: 'Smart Furniture Production',
        description: 'Innovative furniture manufacturing with integrated technology and ergonomic design principles',
        category: 'Furniture',
        features: [
          'Custom furniture design and prototyping',
          'Smart technology integration',
          'Ergonomic and sustainable materials',
          'Quality craftsmanship',
          'Modular and customizable options',
          'Professional installation services'
        ],
        icon: 'furniture',
        image: '/assets/services/furniture.jpg'
      },
      {
        id: 3,
        title: 'Precision Metalworks',
        description: 'Advanced metal fabrication and precision engineering for industrial and commercial applications',
        category: 'Metalworks',
        features: [
          'Custom metal fabrication',
          'Precision engineering and machining',
          'Quality control and testing',
          'Rapid prototyping services',
          'Industrial-grade materials',
          'Technical consultation'
        ],
        icon: 'metalworks',
        image: '/assets/services/metalworks.jpg'
      },
      {
        id: 4,
        title: 'Supply Chain Solutions',
        description: 'End-to-end supply chain management and logistics services for efficient production and delivery',
        category: 'Logistics',
        features: [
          'Inventory management systems',
          'Supplier coordination and management',
          'Quality control throughout the chain',
          'Logistics and distribution',
          'Real-time tracking and monitoring',
          'Cost optimization strategies'
        ],
        icon: 'logistics',
        image: '/assets/services/supply-chain.jpg'
      },
      {
        id: 5,
        title: 'Quality Assurance Services',
        description: 'Comprehensive quality control and testing services ensuring excellence in every product',
        category: 'Quality',
        features: [
          'Comprehensive quality testing',
          'International standards compliance',
          'Material and product certification',
          'Process optimization',
          'Continuous improvement programs',
          'Quality training and consulting'
        ],
        icon: 'quality',
        image: '/assets/services/quality.jpg'
      },
      {
        id: 6,
        title: 'Custom Manufacturing',
        description: 'Tailored manufacturing solutions designed to meet your specific business requirements',
        category: 'Custom',
        features: [
          'Custom product development',
          'Design consultation and prototyping',
          'Scalable production solutions',
          'Technical support and maintenance',
          'After-sales service',
          'Ongoing partnership support'
        ],
        icon: 'custom',
        image: '/assets/services/custom.jpg'
      }
    ];
  }

  @Post('contact')
  @ApiOperation({ summary: 'Submit contact form' })
  @ApiResponse({ status: 201, description: 'Contact form submitted successfully' })
  async submitContactForm(@Body() contactData: any) {
    // Send email notification
    await this.emailService.sendContactFormNotification(contactData);
    
    // Store contact inquiry in database
    await this.customerService.createContactInquiry(contactData);
    
    return {
      success: true,
      message: 'Thank you for your message. We will get back to you soon!'
    };
  }

  @Post('quote-request')
  @ApiOperation({ summary: 'Submit quote request' })
  @ApiResponse({ status: 201, description: 'Quote request submitted successfully' })
  async submitQuoteRequest(@Body() quoteData: any) {
    try {
      const quote = await this.quoteService.create(quoteData);
      return { success: true, quoteId: quote.id };
    } catch (error) {
      throw new InternalServerErrorException('Failed to submit quote request');
    }
  }

  @Post('book-tour')
  @ApiOperation({ summary: 'Book a tour' })
  @ApiResponse({ status: 201, description: 'Tour booked successfully' })
  async bookTour(@Body() tourData: any) {
    try {
      const tour = await this.tourService.create(tourData);
      return { success: true, tourId: tour.id };
    } catch (error) {
      throw new InternalServerErrorException('Failed to book tour');
    }
  }

  @Post('newsletter')
  @ApiOperation({ summary: 'Subscribe to newsletter' })
  @ApiResponse({ status: 201, description: 'Newsletter subscription successful' })
  async subscribeNewsletter(@Body() subscriptionData: any) {
    // Add to newsletter subscription list
    await this.customerService.subscribeNewsletter(subscriptionData.email);
    
    return {
      success: true,
      message: 'Thank you for subscribing to our newsletter!'
    };
  }

  @Get('testimonials')
  @ApiOperation({ summary: 'Get customer testimonials' })
  @ApiResponse({ status: 200, description: 'Returns customer testimonials' })
  async getTestimonials() {
    return [
      {
        id: 1,
        name: 'John Smith',
        company: 'Fashion Forward Ltd',
        role: 'CEO',
        content: 'Monio has transformed our textile production with their innovative approach and commitment to quality.',
        rating: 5,
        image: '/assets/testimonials/john-smith.jpg'
      },
      {
        id: 2,
        name: 'Sarah Johnson',
        company: 'Modern Furniture Co',
        role: 'Procurement Manager',
        content: 'The smart furniture solutions from Monio have exceeded our expectations. Their attention to detail is remarkable.',
        rating: 5,
        image: '/assets/testimonials/sarah-johnson.jpg'
      },
      {
        id: 3,
        name: 'Michael Chen',
        company: 'Industrial Solutions Inc',
        role: 'Operations Director',
        content: 'Monio\'s precision metalworks have been crucial to our manufacturing success. Highly recommended!',
        rating: 5,
        image: '/assets/testimonials/michael-chen.jpg'
      }
    ];
  }

  @Get('portfolio/:id')
  async getProjectById(@Param('id') id: string) {
    try {
      // Mock project data for now - replace with actual service call
      const mockProject = {
        id: parseInt(id),
        title: 'Advanced Manufacturing Facility',
        category: 'Manufacturing',
        client: 'TechCorp Industries',
        location: 'Nairobi, Kenya',
        duration: '18 months',
        budget: '$2.5M',
        description: 'A state-of-the-art manufacturing facility designed for high-volume production with advanced automation and quality control systems.',
        longDescription: `This comprehensive manufacturing facility represents a significant milestone in industrial automation and sustainable production. The project involved the design and construction of a 50,000 square foot facility equipped with cutting-edge manufacturing equipment, automated assembly lines, and integrated quality control systems.

        The facility features advanced robotics, IoT-enabled monitoring systems, and sustainable energy solutions including solar panels and energy-efficient HVAC systems. The project was completed on time and under budget, delivering exceptional value to our client while maintaining the highest standards of quality and safety.`,
        technologies: ['Automation', 'IoT', 'Robotics', 'Quality Control', 'Energy Management'],
        challenges: [
          'Complex automation integration',
          'Strict quality control requirements',
          'Tight timeline constraints',
          'Energy efficiency optimization'
        ],
        solutions: [
          'Modular automation design',
          'Advanced QC protocols',
          'Agile project management',
          'Sustainable energy systems'
        ],
        results: [
          '30% increase in production efficiency',
          '99.9% quality control accuracy',
          '25% reduction in energy costs',
          'Zero safety incidents'
        ],
        image: '/api/uploads/projects/project-1.jpg',
        gallery: [
          '/api/uploads/projects/project-1-1.jpg',
          '/api/uploads/projects/project-1-2.jpg',
          '/api/uploads/projects/project-1-3.jpg',
        ],
        team: [
          { name: 'John Doe', role: 'Project Manager', avatar: '/api/uploads/team/john.jpg' },
          { name: 'Jane Smith', role: 'Lead Engineer', avatar: '/api/uploads/team/jane.jpg' },
          { name: 'Mike Johnson', role: 'Automation Specialist', avatar: '/api/uploads/team/mike.jpg' },
        ],
        completionDate: '2023-12-15',
        status: 'Completed',
      };
      
      return mockProject;
    } catch (error) {
      throw new InternalServerErrorException('Failed to fetch project');
    }
  }

  @Get('stats')
  @ApiOperation({ summary: 'Get company statistics' })
  @ApiResponse({ status: 200, description: 'Returns company statistics' })
  async getCompanyStats() {
    return {
      yearsExperience: 4,
      projectsCompleted: 500,
      happyCustomers: 200,
      teamMembers: 50,
      productionCapacity: '10,000 units/month',
      qualityRating: '99.8%',
      deliveryTime: '2-4 weeks',
      countriesServed: 15
    };
  }
} 