from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from Models.oportunidad_de_venta_model import OportunidadDeVenta
from Models.Empresa import Empresa
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from datetime import datetime
from django.http import HttpResponse
import openpyxl
from io import BytesIO

class ReportsViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_description="Obtiene el informe de Oportunidades de Venta",
        manual_parameters=[
            openapi.Parameter('start_date', openapi.IN_QUERY, description="Fecha inicio (YYYY-MM-DD)", type=openapi.TYPE_STRING),
            openapi.Parameter('end_date', openapi.IN_QUERY, description="Fecha fin (YYYY-MM-DD)", type=openapi.TYPE_STRING),
            openapi.Parameter('export', openapi.IN_QUERY, description="Formato de exportación (opcional, ej: 'excel')", type=openapi.TYPE_STRING),
        ],
        responses={200: "Lista de oportunidades con datos relacionados"}
    )
    @action(detail=False, methods=['get'], url_path='sales')
    def sales_opportunity_report(self, request):
        queryset = OportunidadDeVenta.objects.all().select_related(
            'empresa', 'usuario_responsable', 'estado_oportunidad', 'column_workflow'
        ).filter(deleted_at__isnull=True)

        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        export_format = request.query_params.get('export')

        if start_date:
            queryset = queryset.filter(fecha_creacion__gte=start_date)
        if end_date:
            queryset = queryset.filter(fecha_creacion__lte=end_date)

        if export_format == 'excel':
            response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = f'attachment; filename=informe_oportunidades_{datetime.now().strftime("%Y%m%d")}.xlsx'
            
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = "Oportunidades"
            
            # Headers
            headers = ['ID', 'Nombre', 'Empresa', 'Responsable', 'Estado', 'Valor Estimado', 'Fecha Cierre', 'Etapa', 'Fecha Creación']
            ws.append(headers)
            
            for op in queryset:
                ws.append([
                    op.id,
                    op.nombre,
                    op.empresa.nombre if op.empresa else None,
                    f"{op.usuario_responsable.nombre} {getattr(op.usuario_responsable, 'last_name', '')}".strip() if op.usuario_responsable else None,
                    op.estado_oportunidad.nombre_estado if op.estado_oportunidad else None,
                    op.valor_estimado,
                    op.fecha_estimada_cierre.strftime('%Y-%m-%d') if op.fecha_estimada_cierre else None,
                    op.column_workflow.nombre if op.column_workflow else None,
                    op.fecha_creacion.strftime('%Y-%m-%d') if op.fecha_creacion else None,
                ])
                
            output = BytesIO()
            wb.save(output)
            output.seek(0)
            
            response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = f'attachment; filename=informe_oportunidades_{datetime.now().strftime("%Y%m%d")}.xlsx'
            return response

        data = []
        for op in queryset:
            data.append({
                'id': op.id,
                'nombre': op.nombre,
                'empresa': op.empresa.nombre if op.empresa else None,
                'usuario_responsable': f"{op.usuario_responsable.nombre} {getattr(op.usuario_responsable, 'last_name', '')}".strip() if op.usuario_responsable else None,
                'estado': op.estado_oportunidad.nombre_estado if op.estado_oportunidad else None,
                'valor': op.valor_estimado,
                'fecha_cierre': op.fecha_estimada_cierre,
                'probabilidad': getattr(op, 'probabilidad', None), # Check field existence
                'etapa': op.column_workflow.nombre if op.column_workflow else None,
                'fecha_creacion': op.fecha_creacion
            })
        
        return Response(data)

    @swagger_auto_schema(
        operation_description="Obtiene el informe de Clientes (Empresas)",
        manual_parameters=[
            openapi.Parameter('start_date', openapi.IN_QUERY, description="Fecha inicio (YYYY-MM-DD)", type=openapi.TYPE_STRING),
            openapi.Parameter('end_date', openapi.IN_QUERY, description="Fecha fin (YYYY-MM-DD)", type=openapi.TYPE_STRING),
            openapi.Parameter('export', openapi.IN_QUERY, description="Formato de exportación (opcional, ej: 'excel')", type=openapi.TYPE_STRING),
        ],
        responses={200: "Lista de clientes con datos relacionados o archivo Excel"}
    )
    @action(detail=False, methods=['get'], url_path='clients')
    def clients_report(self, request):
        queryset = Empresa.objects.all().select_related(
            'provincia', 'localidad', 'estado_empresa', 'usuario_responsable'
        ).filter(deleted_at__isnull=True)

        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        export_format = request.query_params.get('export')
        
        print(f"DEBUG CLIENTS REPORT: Query Params: {request.query_params}")
        print(f"DEBUG CLIENTS REPORT: Export Format: {export_format}")

        if start_date:
            queryset = queryset.filter(fecha_creacion__gte=start_date)
        if end_date:
            queryset = queryset.filter(fecha_creacion__lte=end_date)
            
        if export_format == 'excel':
            print("DEBUG: Generating Excel for Clients")
            response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = f'attachment; filename=informe_clientes_{datetime.now().strftime("%Y%m%d")}.xlsx'
            
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = "Clientes"
            
            # Headers
            headers = ['ID', 'Nombre', 'CUIT', 'Estado', 'Provincia', 'Localidad', 'Responsable', 'Fecha Creación', 'Dirección']
            ws.append(headers)
            
            for emp in queryset:
                ws.append([
                    emp.id,
                    emp.nombre,
                    emp.cuit,
                    emp.estado_empresa.nombre_estado if emp.estado_empresa else None,
                    emp.provincia.nombre if hasattr(emp.provincia, 'nombre') else str(emp.provincia),
                    emp.localidad.nombre if hasattr(emp.localidad, 'nombre') else str(emp.localidad),
                    f"{emp.usuario_responsable.nombre} {getattr(emp.usuario_responsable, 'last_name', '')}".strip() if emp.usuario_responsable else None,
                    emp.fecha_creacion.strftime('%Y-%m-%d') if emp.fecha_creacion else None,
                    emp.direccion
                ])
                
            output = BytesIO()
            wb.save(output)
            output.seek(0)
            
            response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = f'attachment; filename=informe_clientes_{datetime.now().strftime("%Y%m%d")}.xlsx'
            return response
            
        data = []
        for emp in queryset:
            data.append({
                'id': emp.id,
                'nombre': emp.nombre,
                'cuit': emp.cuit,
                'estado': emp.estado_empresa.nombre_estado if emp.estado_empresa else None,
                'provincia': emp.provincia.nombre if hasattr(emp.provincia, 'nombre') else str(emp.provincia), 
                'localidad': emp.localidad.nombre if hasattr(emp.localidad, 'nombre') else str(emp.localidad),
                'usuario_responsable': f"{emp.usuario_responsable.nombre} {getattr(emp.usuario_responsable, 'last_name', '')}".strip() if emp.usuario_responsable else None,
                'fecha_creacion': emp.fecha_creacion,
                'direccion': emp.direccion
            })

        return Response(data)
