from django.db import models
from django.urls import reverse
from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField
from wagtail.admin.panels import (
    FieldPanel, MultiFieldPanel, InlinePanel, FieldRowPanel,
    TabbedInterface, ObjectList
)
from wagtail.contrib.settings.models import BaseSiteSetting, register_setting
from wagtail.snippets.models import register_snippet
from wagtail.search import index
from modelcluster.fields import ParentalKey
from taggit.managers import TaggableManager
from ckeditor_uploader.fields import RichTextUploadingField


# ── SITE SETTINGS ────────────────────────────────────────────────────────────
@register_setting
class SiteSettings(BaseSiteSetting):
    """Editable via Wagtail Admin → Settings → Site Settings"""
    class Meta:
        verbose_name = 'Site Settings'

    # Contact
    phone        = models.CharField(max_length=30, default='+233 (0) 249 960 786')
    phone2       = models.CharField(max_length=30, blank=True, default='+233 (0) 277 011 900')
    email        = models.EmailField(default='info@frimpslogistics.com')
    address      = models.CharField(max_length=250, default='Lashibi, Tema, Greater Accra, Ghana GT-363-7107')
    hours        = models.CharField(max_length=100, default='Mon – Sat: 8:00am – 5:00pm')

    # Social — add real URLs here
    facebook  = models.URLField(blank=True, default='https://www.facebook.com/')
    twitter   = models.URLField(blank=True, default='https://www.twitter.com/')
    linkedin  = models.URLField(blank=True, default='https://www.linkedin.com/')
    instagram = models.URLField(blank=True, default='https://www.instagram.com/')
    youtube   = models.URLField(blank=True)
    whatsapp  = models.CharField(max_length=20, blank=True,
                                  help_text='Number only, e.g. 233249960786')

    # Logos (upload replacements in Wagtail)
    logo        = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+',
                                     help_text='Main nav logo')
    footer_logo = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+',
                                     help_text='Footer logo')
    favicon     = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')

    # SEO defaults (per-page overrides these)
    default_seo_title   = models.CharField(max_length=200, blank=True,
                                            default='Frimps Logistics Limited — Logistics Services in Ghana')
    default_description = models.TextField(blank=True,
                                            default="Frimps Logistics Limited is Ghana's trusted logistics, freight forwarding, customs clearance and warehousing company based in Tema, Greater Accra.")
    default_og_image    = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                             on_delete=models.SET_NULL, related_name='+',
                                             help_text='Default social share image (1200×630px)')

    # Google
    google_verification = models.CharField(max_length=200, blank=True,
                                             help_text='Google Search Console HTML tag content= value')
    ga4_id              = models.CharField(max_length=50, blank=True,
                                            help_text='Google Analytics 4 ID, e.g. G-XXXXXXXXXX')

    # Footer
    footer_about = models.TextField(blank=True,
                                     default='Frimps Logistics Limited is a licensed clearing, forwarding and supply chain company in Ghana — providing air freight, ocean freight, road transport, warehousing and customs clearance.')
    footer_copy  = models.CharField(max_length=200, blank=True,
                                     default='© 2025 Frimps Logistics Limited. All Rights Reserved.')

    panels = [
        TabbedInterface([
            ObjectList([
                MultiFieldPanel([
                    FieldPanel('phone'),
                    FieldPanel('phone2'),
                    FieldPanel('email'),
                    FieldPanel('address'),
                    FieldPanel('hours'),
                ], heading='📞 Contact Details'),
            ], heading='Contact'),
            ObjectList([
                MultiFieldPanel([
                    FieldPanel('facebook'),
                    FieldPanel('twitter'),
                    FieldPanel('linkedin'),
                    FieldPanel('instagram'),
                    FieldPanel('youtube'),
                    FieldPanel('whatsapp'),
                ], heading='🌐 Social Media Links'),
            ], heading='Social Media'),
            ObjectList([
                MultiFieldPanel([
                    FieldPanel('logo'),
                    FieldPanel('footer_logo'),
                    FieldPanel('favicon'),
                ], heading='🖼️ Logos & Icons'),
            ], heading='Logos'),
            ObjectList([
                MultiFieldPanel([
                    FieldPanel('default_seo_title'),
                    FieldPanel('default_description'),
                    FieldPanel('default_og_image'),
                ], heading='🔍 Default SEO'),
                MultiFieldPanel([
                    FieldPanel('google_verification'),
                    FieldPanel('ga4_id'),
                ], heading='📊 Google Tools'),
            ], heading='SEO & Analytics'),
            ObjectList([
                FieldPanel('footer_about'),
                FieldPanel('footer_copy'),
            ], heading='Footer'),
        ])
    ]


# ── SEO MIXIN ────────────────────────────────────────────────────────────────
class SEOMixin(models.Model):
    og_title  = models.CharField(max_length=200, blank=True,
                                  help_text='Social share title. Blank = use page title.')
    og_desc   = models.TextField(blank=True,
                                  help_text='Social share description. Blank = use search description.')
    og_image  = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name='+',
                                   verbose_name='Social share image (1200×630px)')
    tw_card   = models.CharField(max_length=30, default='summary_large_image',
                                  choices=[('summary','Summary'),
                                           ('summary_large_image','Large Image')])

    seo_panels = [
        MultiFieldPanel([
            FieldPanel('seo_title'),
            FieldPanel('search_description'),
        ], heading='Search Engine (Google)'),
        MultiFieldPanel([
            FieldPanel('og_title'),
            FieldPanel('og_desc'),
            FieldPanel('og_image'),
            FieldPanel('tw_card'),
        ], heading='Social Media (Open Graph / Twitter Card)'),
    ]

    class Meta:
        abstract = True


# ── SNIPPETS ─────────────────────────────────────────────────────────────────
class Service(models.Model):
    title      = models.CharField(max_length=150)
    slug       = models.SlugField(unique=True)
    icon_path  = models.CharField(max_length=150, default='img/icon/service_1_1.svg',
                                   help_text='Path to icon SVG relative to static root, e.g. img/icon/service_1_1.svg')
    image      = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                    on_delete=models.SET_NULL, related_name='+')
    short_desc = models.TextField(help_text='Short text shown on listing/home pages')
    full_desc  = RichTextField(help_text='Full description on service detail page')
    features   = models.TextField(blank=True,
                                   help_text='One feature per line — shown as checklist')
    order      = models.IntegerField(default=0)
    active     = models.BooleanField(default=True)
    seo_title  = models.CharField(max_length=200, blank=True)
    seo_desc   = models.TextField(blank=True)

    panels = [
        MultiFieldPanel([
            FieldPanel('title'), FieldPanel('slug'),
            FieldRowPanel([FieldPanel('order'), FieldPanel('active')]),
        ], heading='Basic'),
        MultiFieldPanel([
            FieldPanel('icon_path'), FieldPanel('image'),
            FieldPanel('short_desc'), FieldPanel('full_desc'),
            FieldPanel('features'),
        ], heading='Content'),
        MultiFieldPanel([
            FieldPanel('seo_title'), FieldPanel('seo_desc'),
        ], heading='SEO'),
    ]

    def __str__(self): return self.title
    def get_features(self): return [f.strip() for f in self.features.splitlines() if f.strip()]

    class Meta:
        ordering = ['order', 'title']
        verbose_name = 'Service'


class Testimonial(models.Model):
    name    = models.CharField(max_length=100)
    role    = models.CharField(max_length=150)
    content = models.TextField()
    rating  = models.IntegerField(default=5, choices=[(i, f'{i}★') for i in range(1, 6)])
    photo   = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                 on_delete=models.SET_NULL, related_name='+')
    active  = models.BooleanField(default=True)
    order   = models.IntegerField(default=0)

    panels = [
        FieldPanel('name'), FieldPanel('role'), FieldPanel('content'),
        FieldPanel('rating'), FieldPanel('photo'),
        FieldRowPanel([FieldPanel('active'), FieldPanel('order')]),
    ]
    def __str__(self): return f'{self.name}'
    class Meta:
        ordering = ['order']
        verbose_name = 'Testimonial'


# ── TEAM MEMBER (inline on AboutPage) ────────────────────────────────────────
class TeamMember(Orderable):
    page      = ParentalKey('website.AboutPage', related_name='team_members')
    name      = models.CharField(max_length=100)
    role      = models.CharField(max_length=150)
    photo     = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name='+')
    facebook  = models.URLField(blank=True)
    twitter   = models.URLField(blank=True)
    linkedin  = models.URLField(blank=True)
    instagram = models.URLField(blank=True)

    panels = [
        FieldRowPanel([FieldPanel('name'), FieldPanel('role')]),
        FieldPanel('photo'),
        FieldRowPanel([
            FieldPanel('facebook'), FieldPanel('twitter'),
            FieldPanel('linkedin'), FieldPanel('instagram'),
        ]),
    ]

    def __str__(self): return self.name


# ── HERO SLIDE (inline on HomePage) ─────────────────────────────────────────
class HeroSlide(Orderable):
    page       = ParentalKey('website.HomePage', related_name='hero_slides')
    eyebrow    = models.CharField(max_length=150)
    title      = models.CharField(max_length=200)
    subtitle   = models.TextField(blank=True)
    btn_text   = models.CharField(max_length=60, default='Discover More')
    btn_url    = models.CharField(max_length=200, default='/contact/')
    background = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                    on_delete=models.SET_NULL, related_name='+',
                                    help_text='Slide background image')

    panels = [
        FieldPanel('eyebrow'), FieldPanel('title'), FieldPanel('subtitle'),
        FieldPanel('background'),
        FieldRowPanel([FieldPanel('btn_text'), FieldPanel('btn_url')]),
    ]


# ── PAGES ────────────────────────────────────────────────────────────────────
class HomePage(SEOMixin, Page):
    template = 'website/index.html'

    about_title = models.CharField(max_length=300,
                                    default='Reliable Logistics & Transport Solutions in Ghana')
    about_body  = RichTextField(blank=True,
                                 default='<p>Frimps Logistics Limited is a passionate and dedicated company in the clearing and forwarding industry. We are committed to making a positive impact on trade and commerce across Africa. Our values — integrity, speed, and reliability — drive every shipment we handle.</p>')
    about_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')
    why_title   = models.CharField(max_length=200,
                                    default='Why Businesses Choose Frimps Logistics')

    edit_handler = TabbedInterface([
        ObjectList(Page.content_panels + [
            MultiFieldPanel([InlinePanel('hero_slides', label='Hero Slide', min_num=1)],
                            heading='🎯 Hero Slider (3 slides)'),
            MultiFieldPanel([
                FieldPanel('about_title'),
                FieldPanel('about_body'),
                FieldPanel('about_image'),
            ], heading='📋 About Section'),
            FieldPanel('why_title'),
        ], heading='Content'),
        ObjectList(Page.promote_panels + SEOMixin.seo_panels, heading='SEO & Social'),
    ])
    class Meta: verbose_name = 'Home Page'


class AboutPage(SEOMixin, Page):
    template = 'website/about.html'

    # ── Hero / Section heading ─────────────────────────────────────────────────
    section_title = models.CharField(max_length=300,
                                      default='Reliable Logistics & Transport Solutions Since 2010')

    # ── Intro ──────────────────────────────────────────────────────────────────
    intro_body  = RichTextField(blank=True,
                                 default='<p>Frimps Logistics Limited is a passionate and dedicated company in the clearing, forwarding and supply chain industry. Founded in Ghana, we are committed to making a positive impact on trade and commerce across Africa and beyond. Our values — integrity, speed and reliability — drive every shipment we handle and every client relationship we build.</p>')
    intro_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+',
                                     help_text='Large image on the left of the intro section')

    # ── Counters ───────────────────────────────────────────────────────────────
    counter1_num   = models.CharField(max_length=20, default='15k')
    counter1_label = models.CharField(max_length=80, default='Satisfied Clients')
    counter2_num   = models.CharField(max_length=20, default='189k')
    counter2_label = models.CharField(max_length=80, default='Parcels Delivered')

    # ── Checklist ──────────────────────────────────────────────────────────────
    checklist_title = models.CharField(max_length=200,
                                        default='A Company Built on Trust, Speed & Reliability')
    checklist_body  = models.TextField(
        default='With over 15 years of experience in Ghana\'s logistics industry, Frimps Logistics has built a reputation for excellence in freight forwarding, customs clearance and supply chain management. We operate through the Port of Tema and Kotoka International Airport, giving our clients seamless access to global trade routes.')

    # ── CEO ────────────────────────────────────────────────────────────────────
    ceo_name  = models.CharField(max_length=100, default='Emmanuel Frimpong')
    ceo_role  = models.CharField(max_length=150, default='Founder & CEO, Frimps Logistics Limited')
    ceo_photo = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name='+')

    # ── Banner image (replaces video) ─────────────────────────────────────────
    banner_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True,
                                      on_delete=models.SET_NULL, related_name='+',
                                      help_text='Full-width banner image below the features section')

    # ── FAQs ──────────────────────────────────────────────────────────────────
    faq1_q = models.CharField(max_length=200, default='What services does Frimps Logistics provide?')
    faq1_a = models.TextField(default='Frimps Logistics provides air freight, ocean freight, road transportation, warehousing and distribution, customs clearance, and courier and last-mile delivery services across Ghana and internationally.')
    faq2_q = models.CharField(max_length=200, default='Where is Frimps Logistics based and which areas do you serve?')
    faq2_a = models.TextField(default='We are headquartered at Lashibi, Tema, Greater Accra. We serve clients throughout Ghana, across West Africa, and internationally through our global carrier and airline network.')
    faq3_q = models.CharField(max_length=200, default='How do I get a quote for my shipment?')
    faq3_a = models.TextField(default='Simply fill in our contact form, call +233 (0) 249 960 786, or email info@frimpslogistics.com. Our team will prepare a competitive quote within 24 hours.')
    faq4_q = models.CharField(max_length=200, default='Do you handle customs clearance for imported goods?')
    faq4_a = models.TextField(default='Yes. Our GRA-licensed customs brokers handle all import and export documentation, duties, tariff classification and compliance at the Port of Tema and Kotoka International Airport.')

    edit_handler = TabbedInterface([
        ObjectList(Page.content_panels + [
            FieldPanel('section_title'),
            MultiFieldPanel([
                FieldPanel('intro_body'),
                FieldPanel('intro_image'),
            ], heading='📄 Introduction Text & Image'),
            MultiFieldPanel([
                FieldRowPanel([FieldPanel('counter1_num'), FieldPanel('counter1_label')]),
                FieldRowPanel([FieldPanel('counter2_num'), FieldPanel('counter2_label')]),
            ], heading='📊 Counters'),
            MultiFieldPanel([
                FieldPanel('checklist_title'),
                FieldPanel('checklist_body'),
            ], heading='✅ Checklist'),
            MultiFieldPanel([
                FieldPanel('ceo_name'),
                FieldPanel('ceo_role'),
                FieldPanel('ceo_photo'),
            ], heading='👤 CEO / Leadership Profile'),
            FieldPanel('banner_image'),
            MultiFieldPanel([
                InlinePanel('team_members', label='Team Member'),
            ], heading='👥 Team Members'),
        ], heading='Content'),
        ObjectList([
            MultiFieldPanel([FieldRowPanel([FieldPanel('faq1_q')]), FieldPanel('faq1_a')], heading='FAQ 1'),
            MultiFieldPanel([FieldRowPanel([FieldPanel('faq2_q')]), FieldPanel('faq2_a')], heading='FAQ 2'),
            MultiFieldPanel([FieldRowPanel([FieldPanel('faq3_q')]), FieldPanel('faq3_a')], heading='FAQ 3'),
            MultiFieldPanel([FieldRowPanel([FieldPanel('faq4_q')]), FieldPanel('faq4_a')], heading='FAQ 4'),
        ], heading='FAQ Section'),
        ObjectList(Page.promote_panels + SEOMixin.seo_panels, heading='SEO & Social'),
    ])
    class Meta: verbose_name = 'About Page'


class ServiceListPage(SEOMixin, Page):
    template = 'website/service.html'
    content_panels = Page.content_panels
    promote_panels = Page.promote_panels + SEOMixin.seo_panels
    class Meta: verbose_name = 'Services Page'


class ServiceDetailPage(SEOMixin, Page):
    template = 'website/service_details.html'
    service  = models.ForeignKey('website.Service', null=True, blank=True,
                                  on_delete=models.SET_NULL, related_name='+',
                                  help_text='Select the service this page describes')

    content_panels = Page.content_panels + [FieldPanel('service')]
    promote_panels = Page.promote_panels + SEOMixin.seo_panels
    class Meta: verbose_name = 'Service Detail Page'


class BlogPost(models.Model):
    title      = models.CharField(max_length=255)
    slug       = models.SlugField(unique=True, max_length=255)
    date       = models.DateField()
    category   = models.CharField(max_length=80, default='Logistics')
    excerpt    = models.TextField(blank=True)
    body       = RichTextUploadingField()
    hero_image = models.ImageField(upload_to='blog/', blank=True, null=True)
    author     = models.CharField(max_length=100, default='Frimps Logistics Team')
    tags       = TaggableManager(blank=True)
    published  = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def get_absolute_url(self):
        return reverse('blog_detail', kwargs={'slug': self.slug})

    def __str__(self): return self.title
    class Meta: verbose_name = 'Blog Post'; ordering = ['-date']


class ContactPage(SEOMixin, Page):
    template    = 'website/contact.html'
    success_msg = models.TextField(blank=True,
                                    default='Thank you! Your message has been received. We will reply within 24 hours.')

    content_panels = Page.content_panels + [FieldPanel('success_msg')]
    promote_panels = Page.promote_panels + SEOMixin.seo_panels
    class Meta: verbose_name = 'Contact Page'


# ── CONTACT SUBMISSIONS ───────────────────────────────────────────────────────
class ContactSubmission(models.Model):
    name       = models.CharField(max_length=100)
    email      = models.EmailField()
    phone      = models.CharField(max_length=30, blank=True)
    subject    = models.CharField(max_length=200, blank=True)
    message    = models.TextField()
    source     = models.CharField(max_length=50, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    read       = models.BooleanField(default=False)

    def __str__(self): return f'{self.name} — {self.created_at:%d %b %Y}'
    class Meta: ordering = ['-created_at']; verbose_name = 'Contact Submission'
