import axios from 'axios';
import React from 'react';
import {
  publicCoachSite as defaultSite,
  type PublicCoachPackage,
  type PublicCoachSite,
} from '../coachingSite';

type PublishedSettings = {
  published?: boolean;
  practice_name?: string;
  logo_url?: string;
  coach_name?: string;
  coach_photo_url?: string;
  coach_bio?: string;
  coach_credentials?: string;
  coach_niche?: string;
  contact_email?: string;
  default_booking_url?: string | null;
  social_links?: Array<{ label?: string; href?: string }>;
  packages?: Array<{
    slug?: string;
    name?: string;
    description?: string;
    duration?: string;
    price?: string;
    cta_label?: string;
    booking_url?: string | null;
    items?: string[];
  }>;
  testimonials?: Array<{ quote?: string; name?: string; role?: string }>;
};

const PublicCoachSiteContext = React.createContext<PublicCoachSite>(defaultSite);

function packageSlug(name: string, configuredSlug?: string) {
  if (configuredSlug) {
    return configuredSlug;
  }

  return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}

function configuredPackages(settings: PublishedSettings): PublicCoachPackage[] {
  if (!Array.isArray(settings.packages) || settings.packages.length === 0) {
    return defaultSite.packages;
  }

  return settings.packages.map((item) => {
    const name = String(item.name || 'Coaching package').trim();
    const slug = packageSlug(name, item.slug);
    return {
      slug,
      name,
      price: String(item.price || item.duration || 'Coaching'),
      bookingLabel: String(item.cta_label || 'Book a call'),
      bookingPath: String(item.booking_url || ''),
      intakePath: `/intake/?package=${encodeURIComponent(slug)}`,
      copy: String(item.description || ''),
      items: Array.isArray(item.items) ? item.items.map(String) : [],
    };
  });
}

function mergePublishedSettings(settings: PublishedSettings): PublicCoachSite {
  if (!settings.published) {
    return defaultSite;
  }

  const credentials = String(settings.coach_credentials || '')
    .split(/\n|,/)
    .map((item) => item.trim())
    .filter(Boolean);
  const socialLinks = Array.isArray(settings.social_links)
    ? settings.social_links.map((item) => ({
        label: String(item.label || ''),
        href: String(item.href || ''),
      }))
    : [];
  const testimonials = Array.isArray(settings.testimonials) && settings.testimonials.length > 0
    ? settings.testimonials.map((item) => ({
        quote: String(item.quote || ''),
        name: String(item.name || ''),
        role: String(item.role || ''),
      }))
    : [];

  return {
    ...defaultSite,
    workspaceName: String(settings.practice_name || defaultSite.workspaceName),
    logoUrl: String(settings.logo_url || ''),
    contactEmail: String(settings.contact_email || ''),
    calendly: {
      assessmentUrl: String(settings.default_booking_url || ''),
      oneOnOneUrl: String(settings.default_booking_url || ''),
      packageConsultUrl: String(settings.default_booking_url || ''),
    },
    socialLinks,
    coach: {
      ...defaultSite.coach,
      name: String(settings.coach_name || defaultSite.coach.name),
      title: String(settings.coach_niche || defaultSite.coach.title),
      photoUrl: String(settings.coach_photo_url || defaultSite.coach.photoUrl),
      aboutIntro: String(settings.coach_bio || defaultSite.coach.aboutIntro),
      credentials: credentials.length > 0 ? credentials : defaultSite.coach.credentials,
    },
    packages: configuredPackages(settings),
    testimonials,
  };
}

export function PublicCoachSiteProvider({ children }: { children: React.ReactNode }) {
  const [site, setSite] = React.useState(defaultSite);

  React.useEffect(() => {
    axios.get('/coaching-public/site').then((response) => {
      setSite(mergePublishedSettings(response.data));
    }).catch((error) => {
      console.error('Could not load the public workspace configuration', error);
    });
  }, []);

  return (
    <PublicCoachSiteContext.Provider value={site}>
      {children}
    </PublicCoachSiteContext.Provider>
  );
}

export function usePublicCoachSite() {
  return React.useContext(PublicCoachSiteContext);
}
