using kmCommonLibsCore;
using Microsoft.AspNetCore.Components;
using System.ComponentModel.DataAnnotations;
using Telerik.Blazor.Components;
using Telerik.Blazor;
using Telerik.SvgIcons;

namespace SummerBestWebForm2.Components.Pages;

public partial class Home
{
  async Task OnFinishHandler()
  //private void SaveIt()
  {
    using (var em = new kmCommonLibsCore.Emails())
    {
      // Parsing the submitted form to pull the relevant information
      string cardType = isPostcard ? "Postcard" : "Plastic Card";
      string cardDesign = string.Empty;
      if (designOne)
        cardDesign = "A";
      else if (designTwo)
        cardDesign = "B";
      else if (designThree)
        cardDesign = "C";

      // Postcard or Plastic specific options
      string customizationInfo = string.Empty;
      if (isPostcard)
      {
        string verseChoice = string.Empty;
        string sigChoice = string.Empty;

        if (verseOne)
          verseChoice = "1";
        else if (verseTwo)
          verseChoice = "2";
        else if (verseThree)
          verseChoice = "3";

        if (sigOne)
          sigChoice = string.Format("Option D - From Your Friends At:<br />{0}<br />{1}", locationInfo.LocationName, locationInfo.PhoneNumber);
        else if (sigTwo)
          sigChoice = string.Format("Option E - Name: {0}<br />Title: {1}<br />Phone: {2}", customName, customTitle, customPhone);
        else if (sigThree)
          sigChoice = string.Format("Option F - {0}", customSignature);

        // combine these into customizationInfo
        customizationInfo = string.Format("Verse: {0}<br />Signature: {1}", verseChoice, sigChoice);
      }
      else // isPlasticCard
      {
        string smallOfferString = string.Empty;
        string bigOfferString = string.Empty;

        int[] smallIndexes = new int[4];
        int[] bigIndexes = new int[2];

        int smallCount = 0;
        for (int index = 0; index < smallOffers.Length; index++)
        {
          if (smallOffers[index])
          {
            smallIndexes[smallCount] = index;
            smallCount++;
          }
        }

        int bigCount = 0;
        for (int index = 0; index < bigOffers.Length; index++)
        {
          if (bigOffers[index])
          {
            bigIndexes[bigCount] = index;
            bigCount++;
          }
        }

        foreach (int index in smallIndexes)
        {
          switch (index)
          {
            case 0:
              smallOfferString = smallOfferString + "B1 ";
              break;
            case 1:
              smallOfferString = smallOfferString + "B2 ";
              break;
            case 2:
              smallOfferString = smallOfferString + "B3 ";
              break;
            case 3:
              smallOfferString = smallOfferString + "B4 ";
              break;
            case 4:
              smallOfferString = smallOfferString + "B5 ";
              break;
            case 5:
              smallOfferString = smallOfferString + "B6 ";
              break;
            case 6:
              smallOfferString = smallOfferString + "B7 ";
              break;
            case 7:
              smallOfferString = smallOfferString + "B8 ";
              break;
            case 8:
              smallOfferString = smallOfferString + "B9 ";
              break;
            case 9:
              smallOfferString = smallOfferString + "B10 ";
              break;
            case 10:
              smallOfferString = smallOfferString + "B11 ";
              break;
            case 11:
              smallOfferString = smallOfferString + "B12 ";
              break;
          }
        }

        foreach (int index in bigIndexes)
        {
          switch (index)
          {
            case 0:
              bigOfferString = bigOfferString + "A1 ";
              break;
            case 1:
              bigOfferString = bigOfferString + "A2 ";
              break;
            case 2:
              bigOfferString = bigOfferString + "A3 ";
              break;
            case 3:
              bigOfferString = bigOfferString + "A4 ";
              break;
            case 4:
              bigOfferString = bigOfferString + "A5 ";
              break;
            case 5:
              bigOfferString = bigOfferString + "A6 ";
              break;
          }
        }

        customizationInfo = string.Format("Offers: {0} - {1}", bigOfferString, smallOfferString);
      }



      // Logo info
      string logos = string.Empty;
      if (!goodyear && !michelin && !custom)
        logos = "NA";
      else
      {
        if (goodyear)
        {
          logos += "Goodyear";
          if (michelin)
            logos += ", Michelin";
          if (custom)
            logos += ", Custom";
        }
        else if (michelin)
        {
          logos += "Michelin";
          if (custom)
            logos += ", Custom";
        }
        else if (custom)
          logos += "Custom";
      }

      // Payment info
      string paymentMethod = string.Empty;
      if (ccOnFile)
        paymentMethod = "Credit Card on File";
      else if (callWithInfo)
        paymentMethod = "Call With Payment Info";
      else if (check)
        paymentMethod = "Check";

      // Formulating the email to send
      em.Subject = "SBC Order Form Submission";
      em.AddAddress(enuAddressType.From, "support@keymotive.us", "Summer Growth Enrollment");
      em.AddAddress(enuAddressType.To, "support@keymotive.us", "KeyMotive Support");

      string locInfoString = string.Format("<pre>Location Name: {0}<br />Manager: {1}<br />Address: {2}<br />City: {3}<br />State: {4}<br />Zip: {5}<br /><br />Phone Number: {6}<br />Contact Name: {7}<br />Contact Phone: {8}<br />Contact Email: {9}<br />",
          locationInfo.LocationName, locationInfo.Manager, locationInfo.Address, locationInfo.City, locationInfo.State,
          locationInfo.Zip, locationInfo.PhoneNumber, locationInfo.ContactName,
          locationInfo.ContactPhone, locationInfo.ContactEmail);

      string cardInfoString = string.Format("Card type: {0}, Design {1}<br /><br />Customization Options:<br />{2}<br />Logos: {3}<br />",
                                          cardType, cardDesign, customizationInfo, logos);

      string paymentString = string.Format("Payment Method: {0}<br /><br />Requested Quantity: {1}<br />Additional Comments: {2}", paymentMethod, requestedQuantity, additionalComments);
      em.HtmlBody = "<b>You have a new enrollment:</b><br />" + locInfoString + cardInfoString + paymentString + "</pre>";

      try
      {
        em.Send();
        await Console.Out.WriteLineAsync("Done sending");
      }
      catch (Exception e)
      {
        await Console.Out.WriteLineAsync("ERROR: " + e.Message);
      }
      ShowWizard = false;
      await Dialog.AlertAsync("The Registration was submitted successfully", "Done");
    }
  }

  public bool? IsAudienceChoiceValid { get; set; } = false;
  public bool? IsCardChoiceValid { get; set; } = false;

  public bool? IsDesignChoiceValid { get; set; } = false;

  [CascadingParameter]
  public DialogFactory Dialog { get; set; }

  public bool ShowWizard { get; set; } = true;

  public int Value { get; set; } = 0;

  //public TelerikForm RegisterForm { get; set; }
  public User UserModel { get; set; } = new User();

  public TelerikForm IntroForm { get; set; } = new();

  // Variables for selecting between plastic and post
  public TelerikForm cardTypeForm { get; set; } = new();
  public CardType cardType { get; set; } = new CardType();
  public bool isPlasticCard { get; set; } = true;
  public bool isPostcard { get; set; } = false;
  public string audienceType { get; set; } = string.Empty;
  public List<AudienceType> audiences { get; set; } = new List<AudienceType>
  {
    new AudienceType() {AudienceDescription="Send to my BEST CUSTOMERS"},
    new AudienceType() {AudienceDescription="Send to Great Prospects as well as Customers who haven't been in during the past 8 months"}
  };

  // Variables for selecting specific design
  public TelerikForm customizationForm { get; set; } = new();
  public CustomizationOptions custOptions { get; set; } = new CustomizationOptions();
  public bool designOne = true;
  public bool designTwo = false;
  public bool designThree = false;

  // Variables for selecting messaging (postcards only)
  public TelerikForm messagingForm { get; set; } = new();
  public MessagingOptions messagingOptions { get; set; } = new MessagingOptions();
  public bool verseOne = true;
  public bool verseTwo = false;
  public bool verseThree = false;
  public bool sigOne = true;
  public bool sigTwo = false;
  public bool sigThree = false;
  public string customName = string.Empty; // For sig two
  public string customTitle = string.Empty;
  public string customPhone = string.Empty;
  public string customSignature = string.Empty; // For sig three
  public bool isMessagingValid = false;

  // Variables for logo selection
  public TelerikForm logoForm { get; set; } = new();
  public LogoOptions logoOptions { get; set; } = new LogoOptions();
  public bool goodyear = false;
  public bool michelin = false;
  public bool custom = false;
  public bool isLogoValid = false;

  // Variables for offer selection (plastic cards only)
  public TelerikForm offerForm { get; set; } = new();
  public OfferOptions offerOptions { get; set; } = new OfferOptions();
  public bool[] bigOffers = new bool[6];
  public bool[] smallOffers = new bool[12];
  public bool isOfferSelectionValid = false;

  // Location information
  public TelerikForm locationForm { get; set; } = new();
  public LocationInfo locationInfo { get; set; } = new LocationInfo();
  public string locationName { get; set; } = string.Empty;
  public string manager { get; set; } = string.Empty;
  public string address { get; set; } = string.Empty;
  public string city { get; set; } = string.Empty;
  public string state { get; set; } = string.Empty;
  public string zip { get; set; } = string.Empty;
  public string phoneNumber { get; set; } = string.Empty;
  public string contactName { get; set; } = string.Empty;
  public string contactPhone { get; set; } = string.Empty;
  public string contactEmail { get; set; } = string.Empty;
  public bool isLocationInfoValid { get; set; } = false;

  // Payment information
  public TelerikForm paymentForm { get; set; } = new();
  public PaymentInfo paymentInfo { get; set; } = new PaymentInfo();
  public string requestedQuantity = string.Empty;
  public string additionalComments = string.Empty;
  public bool ccOnFile = true;
  public bool callWithInfo = false;
  public bool check = false;


  public void ToggleCardType()
  {
    isPlasticCard = !isPlasticCard;
    isPostcard = !isPostcard;
  }

  public void OnAudienceChoiceStepChange(WizardStepChangeEventArgs args)
  {
    IsAudienceChoiceValid = !string.IsNullOrWhiteSpace(audienceType);
  }
  public void OnCardChoiceStepChange(WizardStepChangeEventArgs args)
  {
    IsCardChoiceValid = true; // This is forced to be true but required nonetheless
    
  }

  public void OnDesignStepChange(WizardStepChangeEventArgs args)
  {
    IsDesignChoiceValid = true; // Same as card choice
  }

  public void OnMessagingStepChange(WizardStepChangeEventArgs args)
  {
    isMessagingValid = true;
  }

  public void OnLogoStepChange(WizardStepChangeEventArgs arg)
  {
    isLogoValid = true;
  }

  public async void OnOfferStepChange(WizardStepChangeEventArgs args)
  {
    if (isPostcard)
    {
      isOfferSelectionValid = true;
    }
    else
    {
      int bigOfferCount = 0;
      foreach (bool selection in bigOffers)
      {
        if (selection)
          bigOfferCount++;
      }

      int smallOfferCount = 0;
      foreach (bool selection in smallOffers)
      {
        if (selection)
          smallOfferCount++;
      }

      if (smallOfferCount == 4 && bigOfferCount == 2)
        isOfferSelectionValid = true;
      else
        isOfferSelectionValid = false;

      if (!isOfferSelectionValid)
      {
        args.IsCancelled = true;
        await Dialog.AlertAsync("Please select the proper amount of offers.", "You cannot proceed");
      }
    }
  }

  public async void OnLocationStepChange(WizardStepChangeEventArgs args)
  {
    isLocationInfoValid = !string.IsNullOrWhiteSpace(locationInfo.ContactEmail) &&
                !string.IsNullOrWhiteSpace(locationInfo.ContactPhone) &&
                !string.IsNullOrWhiteSpace(locationInfo.ContactName) &&
                !string.IsNullOrWhiteSpace(locationInfo.City) &&
                !string.IsNullOrWhiteSpace(locationInfo.State) &&
                !string.IsNullOrWhiteSpace(locationInfo.Zip) &&
                !string.IsNullOrWhiteSpace(locationInfo.PhoneNumber) &&
                !string.IsNullOrWhiteSpace(locationInfo.LocationName) &&
                !string.IsNullOrWhiteSpace(locationInfo.Address) &&
                !string.IsNullOrWhiteSpace(locationInfo.Manager);

    if (!isLocationInfoValid)
    {
      args.IsCancelled = true;
      await Dialog.AlertAsync("Please fill out all required fields.", "You cannot proceed");
    }
  }

  #region "Models and Such"

  public class CardType
  {
    [Required]
    public string cardChoice { get; set; } = string.Empty;
  }

  public class CustomizationOptions
  {
    [Required]
    public string custOption { get; set; } = string.Empty;
  }

  public class MessagingOptions
  {
    public string verse { get; set; } = string.Empty;
    public string signature { get; set; } = string.Empty;
  }

  public class LogoOptions
  {
    public string option { get; set; } = string.Empty;
  }

  public class OfferOptions
  {
    public string option { get; set; } = string.Empty;
  }

  public class LocationInfo
  {
    [Required]
    public string LocationName { get; set; } = string.Empty;
    [Required]
    public string Manager { get; set; } = string.Empty;
    [Required]
    public string Address { get; set; } = string.Empty;
    [Required]
    public string City { get; set; } = string.Empty;
    [Required]
    public string State { get; set; } = string.Empty;
    [Required]
    public string Zip { get; set; } = string.Empty;
    [Required]
    public string PhoneNumber { get; set; } = string.Empty;
    [Required]
    public string ContactName { get; set; } = string.Empty;
    [Required]
    public string ContactPhone { get; set; } = string.Empty;
    [Required]
    public string ContactEmail { get; set; } = string.Empty;
  }

  public class PaymentInfo
  {
    public string info { get; set; } = string.Empty;
  }

  public class AudienceType
  {
    public string AudienceDescription { get; set; } = string.Empty;
  }
  #endregion
}
