from django.db import models

# Create your models here.
from wagtail import blocks
from wagtail.admin.panels import (
    TabbedInterface, ObjectList, FieldPanel, InlinePanel, MultiFieldPanel, FieldRowPanel,
    # import PublishingPanel:
    PublishingPanel,
)

from wagtail.fields import StreamField
from wagtail.models import Page,  PreviewableMixin, Orderable, PageManager
from wagtail_trash.managers import TrashManager
from wagtail.search import index
from wagtail.snippets.models import register_snippet

from wagtail.fields import RichTextField
# from wagtailmodelchooser import register_model_chooser

import re
from django import forms
from django.core.validators import MaxValueValidator, MinValueValidator
from wagtail.models import PreviewableMixin

from .blocks import *
from wagtail.documents import get_document_model
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify

import uuid

from wagtailmodelchooser.blocks import ModelChooserBlock
from wagtail_color_panel.fields import ColorField
from wagtail_color_panel.edit_handlers import NativeColorPanel
from django.core.cache import cache

from .abstract import AbstractCarousel
from wagtail.api import APIField
from wagtail.images.api.fields import ImageRenditionField
from django_extensions.db.fields import AutoSlugField
from modelcluster.models import ClusterableModel
from wagtail.models import Page,  PreviewableMixin, Orderable, PageManager
from modelcluster.fields import ParentalKey
from wagtailmodelchooser.blocks import ModelChooserBlock
from wagtail_color_panel.fields import ColorField
from wagtailmodelchooser import register_model_chooser
from wagtail.documents.models import Document
from .panels import SubcategoryChooser
from django.utils.text import slugify

@register_snippet
@register_model_chooser
class Social(Orderable):
    soTitle = models.CharField(blank=True, null=True,
                               max_length=255,
                               help_text="Social Plateform Name e.g: Facebook,Instagram",
                               verbose_name="Title"
                               )
    soLogo = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
        verbose_name="Icon"
    )
    soLogoText = models.CharField(
        max_length=250, blank=True, null=True, verbose_name="Logo Text")

    soUrl = models.CharField(
        null=True,
        verbose_name="URL",
        max_length=255,
        help_text="For Whatsapp use https://wa.me/8859XXXXXX",
    )
    BgColor = ColorField(default="#FFFFFF", verbose_name="BG")
    FgColor = ColorField(default="#000000", verbose_name="FG")

    hoverBgColor = ColorField(default="#FFFFFF", verbose_name="BG")
    hoverFgColor = ColorField(default="#000000", verbose_name="FG")

    panels = [
        MultiFieldPanel([
            FieldPanel("soTitle"),
            FieldRowPanel(
                [
                    FieldPanel("soLogo"),
                    FieldPanel("soLogoText"),

                ]
            ),
            FieldPanel("soUrl"),
        ]),
        # MultiFieldPanel([
        #     FieldRowPanel(
        #         [
        #             NativeColorPanel('BgColor'),
        #             NativeColorPanel('FgColor')
        #         ]
        #     )
        # ], heading="Color"),

        # MultiFieldPanel([
        #     FieldRowPanel(
        #         [
        #             NativeColorPanel('hoverBgColor'),
        #             NativeColorPanel('hoverFgColor')
        #         ]
        #     )
        # ], heading="Hover")
    ]
    api_fields = [
        APIField('soTitle'),
        APIField('soLogo'),
        APIField('soLogoText'),
        APIField('soUrl'),
        # APIField('BgColor'),
        # APIField('FgColor'),
        # APIField('hoverBgColor'),
        # APIField('hoverFgColor'),
    ]

    def __str__(self):
        return f'{self.soTitle}'

    class Meta:
        verbose_name_plural = "Social"
        ordering = ['soTitle']

    # comp=models.ForeignKey(Company,on_delete=models.PROTECT,related_name="service_cat")

@register_model_chooser
class ServiceCat(ClusterableModel):
    title=models.CharField(max_length=200)
    slug = AutoSlugField(populate_from='title',editable=True,unique=True)
    
    imgIcon = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Image Icon"
    )
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Service Image"
    )
    short_desc = RichTextField(blank=True, null=True,verbose_name="Short Description")
    detail = RichTextField(blank=True, null=True)
    def __str__(self):
        return f"{self.title}"
    content_panels=[
        MultiFieldPanel([
            FieldRowPanel([
            'title',
            ]),
            FieldRowPanel([
            
            'slug','image'
            ]),
            
                'short_desc','detail'
           
        ])
    ]
    sub_cat_panel=[
        InlinePanel('services')
    ]
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Category'),
        ObjectList(sub_cat_panel, heading='Services'),
    ])

@register_model_chooser
class Services(Orderable):
    cat=ParentalKey(ServiceCat,related_name="services")
    title = models.CharField(max_length=200)
    title_animation = models.CharField(
        choices=[
            ('l2r', 'Left to Right'),
            ('r2l', 'Right to Left'),
            ('t2b', 'Top to Bottom'),
            ('b2t', 'Bottom to Top')
        ],
        default="l2r",
        blank=True, null=True, max_length=200
    )
    title_duration = models.IntegerField(default=2, blank=True, null=True)
    
    icon = models.CharField(max_length=200, blank=True, null=True)
    slug = models.CharField(max_length=255, unique=True, blank=True)

    imgIcon = models.ForeignKey(
        "wagtailimages.Image", on_delete=models.SET_NULL, blank=True, null=True, related_name='+', verbose_name="Image Icon"
    )
    image = models.ForeignKey(
        "wagtailimages.Image", on_delete=models.SET_NULL, blank=True, null=True, related_name='+', verbose_name="Service Image"
    )
    img_animation = models.CharField(
        choices=[('l2r', 'Left to Right'), ('r2l', 'Right to Left'), ('t2b', 'Top to Bottom'), ('b2t', 'Bottom to Top')],
        default="l2r", blank=True, null=True, max_length=200
    )
    img_duration = models.IntegerField(default=2, blank=True, null=True)
    
    short_desc = RichTextField(blank=True, null=True, verbose_name="Short Description")
    detail = RichTextField(blank=True, null=True)
    detail_animation = models.CharField(
        choices=[('l2r', 'Left to Right'), ('r2l', 'Right to Left'), ('t2b', 'Top to Bottom'), ('b2t', 'Bottom to Top')],
        default="l2r", blank=True, null=True, max_length=200
    )
    detail_duration = models.IntegerField(default=2, blank=True, null=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            # Generate a base slug from the title
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            # Check for uniqueness and append a number if needed
            while Services.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base_slug}-{counter}"
                counter += 1
            self.slug = slug
        super().save(*args, **kwargs)

    panels = [
        MultiFieldPanel([
            FieldRowPanel(['title', 'slug']),
            FieldRowPanel(['title_animation', 'title_duration']),
            FieldRowPanel(['icon', 'imgIcon', 'image']),
            FieldRowPanel(['img_animation', 'img_duration']),
            'short_desc', 'detail',
            FieldRowPanel(['detail_animation', 'detail_duration'])
        ])
    ]
    
    
class ServiceSubCat(ClusterableModel,Orderable):
    cat=ParentalKey(ServiceCat,related_name="sub_categories")
    title=models.CharField(max_length=200)
    slug = AutoSlugField(populate_from='title',editable=True,unique=True)
    imgIcon = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Image Icon"
    )
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Service Image"
    )
    short_desc = RichTextField(blank=True, null=True)
    detail = RichTextField(blank=True, null=True)
    def __str__(self):
        return f"{self.title}"
    content_panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'title','slug'
            ]),
                'image','short_desc','detail'
           
        ])
    ]
    service_panel=[
        'services'
    ]
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(service_panel, heading='Services'),
    ])
  
@register_snippet
@register_model_chooser
class Menu(ClusterableModel):
    title=models.CharField(max_length=150)
    icon=models.CharField(max_length=150,blank=True,null=True)
    imgIcon = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Image Icon"
    )
    slug = AutoSlugField(populate_from='title',editable=True,blank=True,null=True)
    page=models.ForeignKey('wagtailcore.page',on_delete=models.SET_NULL,null=True,blank=True)
    is_dropdown=models.BooleanField(blank=True,null=True,default=False)
    color = ColorField(
        default="#000000", verbose_name="Color", blank=True, null=True)

    def __str__(self):
        return f"{self.title}"
    panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'title',
                'slug'
            ]),
            FieldRowPanel([
                # FieldPanel('is_dropdown',widget=forms.CheckboxInput()),
                'icon','imgIcon'
            ]),'page'
           
        ]),
        InlinePanel('menu_items',label="Sub Menu")
       
    ]
    class Meta:
        verbose_name="Menu"


@register_model_chooser
class MenuItem(Orderable):
    menu=ParentalKey(Menu,related_name="menu_items",verbose_name="Sub Menu")
    title=models.CharField(max_length=150,blank=True,null=True)
    icon=models.CharField(max_length=150,blank=True,null=True)
    imgIcon = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Image Icon"
    )
    slug = AutoSlugField(populate_from='title',editable=True,blank=True,null=True)
    page=models.ForeignKey('wagtailcore.page',on_delete=models.SET_NULL,null=True,blank=True)
    service=models.ForeignKey('web.Services',on_delete=models.SET_NULL,null=True,blank=True,verbose_name="Service")
    document=models.ForeignKey(Document,on_delete=models.SET_NULL,null=True,blank=True)
    def __str__(self):
        return f"{self.title}"
    panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'title',
                'slug',
            ]),
            FieldRowPanel([
                'icon','imgIcon'
            ]),
             FieldRowPanel([
                  SubcategoryChooser(
                    "service", 
                    category=ServiceCat, 
                    subcategory=Services, 
                    subcategory_related_name="services", 
                    search_text="Search Services"
                ),
                  
                'document','page'
            ]),
        ]),
    ]




@register_snippet
class Header(models.Model):
    title=models.CharField(max_length=200,unique=True,choices=[('Top Header','Top Header'),('Header','Header'),('Mobile Header','Mobile Header'),('Bottom Menu','Bottom Menu'),('Burger Menu','Burger Menu')])
    fontType = models.CharField(
        max_length=200, choices=FONT_TYPE_LIST, blank=True, null=True)
    size = models.CharField(
        max_length=200, choices=FONT_SIZE_LIST, blank=True, null=True,default="text-sm")
    content = StreamField([
        ('row', StructBlock([
            ('bgColor',NativeColorBlock(default="#FFFFFF",label="BG Color")),
            ('fgColor',NativeColorBlock(default="#000000",label="FG Color")),
            ('hoverBgColor',NativeColorBlock(default="#000000",label="Hover BG Color")),
            ('hoverFgColor',NativeColorBlock(default="#FFFFFF",label="Hover FG Color")),
            ('content',StreamBlock([
                ('column', StreamBlock(
                    [
                        ('company_info',StreamBlock([
                            ('email',CompEmailChooserBlock('web.Company')),
                            ('contact',CompContactChooserBlock('web.Company')),
                            ('web',CompWebChooserBlock('web.Company')),
                            ('logo',CompLogoChooserBlock('web.Company')),
                            ('fav',CompFavChooserBlock('web.Company')),
                        ])),
                        ('social', SocialBlock()),
                        # ('logo',CustomSiteLogoChooserBlock('core.SiteLogo')),
                        ('menu', CustomMenuChooserBlock(Menu)),
                        ('page',CustomPageChooserBlock(required=False)),
                        ('show_login', BooleanBlock(required=False,default=False)),
                        ('show_search', BooleanBlock(required=False,default=False)),
                        ('show_burger_menu', BooleanBlock(required=False,default=False)),
                        ('show_get_quote', BooleanBlock(required=False,default=False)),
                    ], required=False
                )),
            ]))
        ])),
    ], blank=True, null=True, use_json_field=True)
    
    
    iconBG=ColorField(default="#cc3d00")
    iconFG=ColorField(default="#FFFFFF")
    iconHoverBG=ColorField(default="#cc3d00")
    iconHoverFG=ColorField(default="#FFFFFF")
    icon=models.CharField(max_length=200,blank=True,null=True)
    shape=models.CharField(max_length=200,blank=True,null=True,default="Circle",choices=[('Circle','Circle'),('Rounded Square','Rounded Square')])
    
    api_fields = [
        APIField('title'),
        APIField('fontType'),
        APIField('size'),
        APIField('content'),
    ]
    content_panels = [
        MultiFieldPanel(
            [
                FieldRowPanel(
                    [
                        FieldPanel('title'),
                        FieldPanel('size'),
                    ]
                ),
                FieldPanel('content', heading="Body")
            ]
        )
    ]
    
    btn_panel=[
        MultiFieldPanel([
            FieldRowPanel([
            'icon',FieldPanel('shape',widget=forms.RadioSelect())
            ]),
            FieldRowPanel([
                NativeColorPanel('iconBG',heading="Background Color"),
                NativeColorPanel('iconFG',heading="Icon Color"),
            ]),
             FieldRowPanel([
                NativeColorPanel('iconHoverBG',heading="Hover Background Color"),
                NativeColorPanel('iconHoverFG',heading="Hover Icon Color"),
            ])
        ])
    ]
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(btn_panel, heading='Corner Button'),
    ])
    def __str__(self):
        return f"{self.title}"
    class Meta:
        verbose_name_plural="Header Settings"


@register_snippet
@register_model_chooser
class Policy(models.Model):
    # comp=models.ForeignKey('web.Company',on_delete=models.PROTECT,related_name="policies")
    title=models.CharField(max_length=200,unique=True)
    slug = AutoSlugField(populate_from='title',editable=True,unique=True)
    detail = RichTextField(blank=True, null=True)
    def __str__(self):
        return f"{self.title}"
    class Meta:
        verbose_name="Policy"
        verbose_name_plural="Policies"


@register_snippet
class BottomFooter(models.Model):
    # comp=models.ForeignKey('web.Company',on_delete=models.PROTECT,related_name="bottom_footer")
    bgColor = ColorField(default="#FFFFFF", verbose_name="BG Color")
    fgColor = ColorField(default="#000000", verbose_name="FG Color")
    fontType = models.CharField(
        max_length=200, choices=FONT_TYPE_LIST, blank=True, null=True,verbose_name="Font Type")
    size = models.CharField(
        max_length=200, choices=FONT_SIZE_LIST, blank=True, null=True,default="text-sm")
    content = StreamField([
        ('row', StreamBlock([
            ('column', StreamBlock(
                [
                    ('policy', CustomPolicyChooserBlock(Policy)),
                    ('paragraph', RichTextBlock()),
                ], required=False
            )),
        ])),
    ], blank=True, null=True, use_json_field=True)
    
    panels = [
        MultiFieldPanel(
            [
                FieldRowPanel(
                    [
                        NativeColorPanel('bgColor'),
                        NativeColorPanel('fgColor'),
                        FieldPanel('size'),
                        FieldPanel('fontType'),
                    ]
                ),
                FieldPanel('content', heading="Body")
            ]
        )
    ]

    class Meta:
        verbose_name_plural="Bottom Footer"


@register_model_chooser
class Company(ClusterableModel):
    coName=models.CharField(max_length=200,verbose_name="Company Name")
    coEmail=models.EmailField(blank=True,null=True,verbose_name="Company Email")
    coContact=models.CharField(max_length=200,blank=True,null=True,verbose_name="Company Contact")
    coWeb=models.CharField(max_length=200,blank=True,null=True,verbose_name="Company Website")
    coLogo = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Company Logo"
    )
    coFav = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL,blank=True,null=True, related_name='+',verbose_name="Company Favicon"
    )
    def __str__(self):
        return f"{self.coName}"
    content_panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'coName','coEmail'
            ]),
            FieldRowPanel([
                'coContact','coWeb'
            ]),
              FieldRowPanel([
                'coLogo','coFav'
            ])
        ])
    ]
    loc_panel=[
        InlinePanel('com_loc',label="Company Location")
    ]
    contact_panel=[
        'contacts'
    ]
    clients_panel=[
        'clients'
    ]
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Company'),
        ObjectList(loc_panel, heading='Location'),
        ObjectList(contact_panel, heading='Contact'),
        ObjectList(clients_panel, heading='Clients'),
    ])

class CompanyLoc(Orderable):
    comp=ParentalKey(Company,related_name="com_loc")
    coLocType=models.CharField(max_length=200,verbose_name="Location Type")
    coLocAdd=models.TextField(blank=True,null=True,verbose_name="Address")
    coLocState=models.CharField(max_length=200,blank=True,null=True,verbose_name="State")
    coLocPin=models.IntegerField(blank=True,null=True,verbose_name="PIN")
    panels=[
        MultiFieldPanel([
            'coLocType','coLocAdd',
            FieldRowPanel([
                'coLocState','coLocPin'
            ])
        ])
    ]
class CompanyContact(Orderable):
    comp=ParentalKey(Company,related_name="contacts")
    coContactName=models.CharField(max_length=200,verbose_name="Contact Person Name")
    coContactEmail=models.EmailField(blank=True,null=True,verbose_name="Email")
    coContactPhone=models.CharField(max_length=13,blank=True,null=True,verbose_name="Phone")
    panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'coContactName','coContactPhone'
            ]),'coContactEmail'
        ])
    ]
@register_snippet
class Industry(models.Model):
    industryName=models.CharField(max_length=200,verbose_name="Industry Name")
    industryImage = models.ForeignKey(
            'wagtailimages.Image', on_delete=models.CASCADE, related_name='+',verbose_name="Industry Image"
    )
    industryDetail=RichTextField(blank=True,null=True,verbose_name="Industry Detail")
    def __str__(self):
        return f"{self.industryName}"
    class Meta:
        verbose_name="Industry"
        verbose_name_plural="Industries"

class CompanyClient(Orderable):
    comp=ParentalKey(Company,related_name="clients")
    coClientName=models.CharField(max_length=200,verbose_name="Client Name")
    coClientCompName=models.CharField(max_length=200,blank=True,null=True,verbose_name="Client Company Name")
    coClientLoc=models.TextField(blank=True,null=True,verbose_name="Address")
    coClientCompImage = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.CASCADE, related_name='+',verbose_name="Client Company Logo"
    )
    panels=[
        MultiFieldPanel([
            FieldRowPanel([
                'coClientName','coClientCompName'
            ]),
            FieldRowPanel([
                'coClientLoc','coClientCompImage'
            ]
            )
        ])
    ]


class WebPage(AbstractCarousel, Page):
    template = "DetailPage/WebPage.html"
    objects = PageManager()  # needed, so _default_manager isn't the trash manager
    objects_excluding_trash = TrashManager()
    body = StreamField([
        ('section', SectionBlock()),
        ('row', RowBlock()),
    ], blank=True, null=True, use_json_field=True)

    show_footer = models.BooleanField(blank=True, null=True, default=False)
    show_footer_menu = models.BooleanField(
        blank=True, null=True, default=False)
    menuIcon = models.CharField(
        max_length=250, blank=True, null=True, verbose_name="Menu Icon")
    menuName = models.CharField(
        max_length=100, null=True, blank=True, verbose_name="Menu Name")
    
    # modify your content_panels:
    api_fields = [
        APIField('body'),
        # APIField('search_image'),
        APIField('bannercontent'),
    ]
    content_panels = Page.content_panels + [
        # FieldPanel('search_image',heading="Title Image"),
        FieldPanel('body'),
        FieldPanel('show_footer'),
        FieldPanel('show_footer_menu', heading="Show in Footer Menu"),
        FieldPanel('menuIcon'),

    ]
    
    banner_panel = [
        MultiFieldPanel([
            # FieldRowPanel([
            #     FieldPanel('bannerHeight'),
            #     FieldPanel('bannerWidth'),
            #     FieldPanel('bannerTimer'),
            # ]),
            FieldPanel('bannercontent')
        ])
    ]
    
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(banner_panel, heading='Banner'),
        ObjectList(Page.promote_panels, heading='Promote'),
    ])
    def get_absolute_url(self):
        return self.url


@register_snippet
class Footer(models.Model):
    title=models.CharField(default="Footer",max_length=200)
    body = StreamField([
        ('row', FooterRowBlock()),
    ], blank=True, null=True, use_json_field=True)
    def __str__(self):
        return f"{self.title}"
    panels = Page.content_panels + [
        FieldPanel('body'),
    ]
    class Meta:
        verbose_name_plural="Footer"



class Enquiry(models.Model):
    id = models.UUIDField(unique=True, primary_key=True, editable=False,
                          default=uuid.uuid4, verbose_name='Public identifier')
    enqName = models.CharField(max_length=100, null=True, blank=True,verbose_name="Name")
    enqEmail = models.EmailField(null=True, blank=True)
    enqContact = models.CharField(max_length=20, null=True, blank=True,verbose_name="Contact")
    enqCompany = models.CharField(max_length=100, null=True, blank=True)
    enqMessage = models.TextField(null=True, blank=True)
    enqCreatedOn = models.DateTimeField(auto_now_add=True,verbose_name="Date")
    enqStatus = models.CharField(
        max_length=100, null=True, blank=True, default="Pending")
    parent = models.ForeignKey(
        'self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
    # enqProduct = models.ForeignKey(
    #     Products, on_delete=models.CASCADE, null=True, blank=True)
    enqProduct = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        if self.parent == None:
            return f'{self.enqName}'
        else:
            return f'{self.parent}  => {self.enqName}'

    class Meta:
        ordering = ['-enqCreatedOn']


class FollowUp(models.Model):
    id = models.UUIDField(unique=True, primary_key=True, editable=False,
                          default=uuid.uuid4, verbose_name='Public identifier')
    enquiry = models.ForeignKey(
        Enquiry, on_delete=models.CASCADE, null=True, blank=True,related_name="followup")
    detail = RichTextField(null=True, blank=True)
    assignTo = models.CharField(max_length=200, null=True, blank=True)
    remarks = models.TextField(null=True, blank=True)
    enqCreatedOn = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey(
        'self', on_delete=models.CASCADE, null=True, blank=True, related_name='replie_follow')

    def __str__(self):
        if self.parent == None:
            return f'{self.assignTo}'
        else:
            return f'{self.enquiry}  => {self.parent} => {self.assignTo}'

    class Meta:
        ordering = ['-enqCreatedOn']
