// src/app/page.tsx
"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

// Define TypeScript interfaces for our data
interface Category {
  id: number;
  name: string;
  description: string | null;
  status: boolean;
  sort_order: number;
  primary_options?: PrimaryOption[];
  secondary_options?: SecondaryOption[];
}

interface PrimaryOption {
  id: number;
  name: string;
  description: string | null;
  price: string | number;
  status: boolean;
  sort_order: number;
  pivot: {
    category_id: number;
    primary_option_id: number;
    is_required: number; // 0 or 1
    is_selected_by_default: number; // 0 or 1
  };
}

interface SecondaryOption {
  id: number;
  name: string;
  description: string | null;
  price: string | number;
  status: boolean;
  sort_order: number;
  pivot: {
    category_id: number;
    secondary_option_id: number;
    is_required: number; // 0 or 1
    is_selected_by_default: number; // 0 or 1
  };
}

interface CountryModule {
  id: number;
  country_name: string;
  module_name: string;
  description: string;
  image_path: string | null;
  price: number | string;
  is_active: boolean;
}

export default function Home() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [countryModules, setCountryModules] = useState<CountryModule[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedOptions, setSelectedOptions] = useState<{ [key: string]: boolean }>({});
  const [country, setCountry] = useState("Belgium");
  const [showTooltip, setShowTooltip] = useState<string | null>(null);
  const router = useRouter();

  // Fetch categories and country modules on component mount
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        // Fetch categories
        const categoriesResponse = await fetch('/api/categories');
        if (!categoriesResponse.ok) {
          throw new Error('Failed to fetch categories');
        }
        const categoriesData = await categoriesResponse.json();
        console.log("Categories data:", categoriesData);

        // Set the fetched data to state
        setCategories(categoriesData.data || []);

        // Fetch country modules
        const countryModulesResponse = await fetch('/api/country-modules');
        if (!countryModulesResponse.ok) {
          throw new Error('Failed to fetch country modules');
        }
        const countryModulesData = await countryModulesResponse.json();
        console.log("Country modules data:", countryModulesData);
        setCountryModules(countryModulesData.data || []);

        // Initialize selected options based on default values
        initializeSelectedOptions(categoriesData.data || []);

      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
        console.error('Error fetching data:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // Initialize selected options based on categories and their default options
  const initializeSelectedOptions = (categories: Category[]) => {
    if (!categories.length) return;

    // Find default category or use the first one
    const defaultCategory = categories.find(cat => cat.status) || categories[0];
    if (defaultCategory) {
      setSelectedCategory(defaultCategory.id);

      // Initialize options object
      const initialOptions: { [key: string]: boolean } = {};

      // Set default primary options
      if (defaultCategory.primary_options && Array.isArray(defaultCategory.primary_options)) {
        defaultCategory.primary_options.forEach(option => {
          // If required or selected by default, mark as selected
          initialOptions[`primary_${option.id}`] = option.pivot.is_required === 1 || option.pivot.is_selected_by_default === 1;
        });
      }

      // Set default secondary options
      if (defaultCategory.secondary_options && Array.isArray(defaultCategory.secondary_options)) {
        defaultCategory.secondary_options.forEach(option => {
          // If required or selected by default, mark as selected
          initialOptions[`secondary_${option.id}`] = option.pivot.is_required === 1 || option.pivot.is_selected_by_default === 1;
        });
      }

      setSelectedOptions(initialOptions);
    }
  };

  // Calculate the sum based on selected options
  const calculateSum = () => {
    if (!selectedCategory) return 0;

    let sum = 0;
    const category = categories.find(cat => cat.id === selectedCategory);

    if (!category) return 0;

    // Add primary options prices
    if (category.primary_options && Array.isArray(category.primary_options)) {
      category.primary_options.forEach(option => {
        if (selectedOptions[`primary_${option.id}`]) {
          sum += parseFloat(option.price.toString());
        }
      });
    }

    // Add secondary options prices
    if (category.secondary_options && Array.isArray(category.secondary_options)) {
      category.secondary_options.forEach(option => {
        if (selectedOptions[`secondary_${option.id}`]) {
          sum += parseFloat(option.price.toString());
        }
      });
    }

    // Add country module price if selected
    const selectedCountryModule = countryModules.find(
      module => module.country_name === country && module.is_active
    );

    if (selectedCountryModule) {
      sum += parseFloat(selectedCountryModule.price.toString());
    }

    return sum;
  };

  const totalSum = calculateSum();

  const handleCategoryChange = (categoryId: number) => {
    if (categoryId === selectedCategory) return;

    setSelectedCategory(categoryId);

    // Reset options based on the newly selected category
    const category = categories.find(cat => cat.id === categoryId);
    if (category) {
      const newOptions: { [key: string]: boolean } = {};

      // Set default primary options
      if (category.primary_options && Array.isArray(category.primary_options)) {
        category.primary_options.forEach(option => {
          // If required or selected by default, mark as selected
          newOptions[`primary_${option.id}`] = option.pivot.is_required === 1 || option.pivot.is_selected_by_default === 1;
        });
      }

      // Set default secondary options
      if (category.secondary_options && Array.isArray(category.secondary_options)) {
        category.secondary_options.forEach(option => {
          // If required or selected by default, mark as selected
          newOptions[`secondary_${option.id}`] = option.pivot.is_required === 1 || option.pivot.is_selected_by_default === 1;
        });
      }

      setSelectedOptions(newOptions);
    }
  };

  const handleOptionChange = (optionType: string, optionId: number) => {
    const optionKey = `${optionType}_${optionId}`;

    // Find the category and option
    const category = categories.find(cat => cat.id === selectedCategory);
    if (!category) return;

    let option;
    if (optionType === 'primary' && category.primary_options) {
      option = category.primary_options.find(opt => opt.id === optionId);
    } else if (optionType === 'secondary' && category.secondary_options) {
      option = category.secondary_options.find(opt => opt.id === optionId);
    }

    // If option is required, don't allow unchecking
    if (option?.pivot.is_required === 1 && selectedOptions[optionKey]) {
      return;
    }

    setSelectedOptions({
      ...selectedOptions,
      [optionKey]: !selectedOptions[optionKey]
    });
  };

  const handleCountryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setCountry(e.target.value);
  };


  const handleSubmit = async () => {
    if (!selectedCategory) {
      alert("Please select a category");
      return;
    }

    try {
      setSubmitting(true);

      const selectedCountryModule = countryModules.find(
        (module) => module.country_name === country && module.is_active
      );

      const currentCategory = categories.find((cat) => cat.id === selectedCategory);

      if (!currentCategory) {
        throw new Error("Selected category not found");
      }

      const selectedPrimaryOptionIds =
        currentCategory.primary_options
          ?.filter((option) => selectedOptions[`primary_${option.id}`])
          .map((option) => option.id) || [];

      const selectedSecondaryOptionIds =
        currentCategory.secondary_options
          ?.filter((option) => selectedOptions[`secondary_${option.id}`])
          .map((option) => option.id) || [];

      const orderData = {
        user_id: 1,
        total_amount: totalSum,
        status: "pending",
        selected_options: {
          category_id: currentCategory.id,
          primary_options: selectedPrimaryOptionIds,
          secondary_options: selectedSecondaryOptionIds,
          country_module_id: selectedCountryModule?.id || null,
        },
      };

      console.log("Submitting order:", orderData);

      const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(orderData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to create order");
      }

      const result = await response.json();
      console.log("Order created:", result);

      const currentParams = new URLSearchParams(window.location.search);

      for (const [key, value] of currentParams.entries()) {
        const cleanValue = value.replace(/&amp;|&amp%3B/g, "&");
        currentParams.set(key, cleanValue);
      }

      const newParams = new URLSearchParams({
        total_amount: orderData.total_amount.toFixed(2),
        category_id: orderData.selected_options.category_id.toString(),
        primary_options: JSON.stringify(orderData.selected_options.primary_options),
        secondary_options: JSON.stringify(orderData.selected_options.secondary_options),
        country_module_id: orderData.selected_options.country_module_id?.toString() || "",
      });

      for (const [key, value] of newParams.entries()) {
        currentParams.set(key, value);
      }

      router.push(`https://client.ebiziner.com/processing.php?${currentParams.toString()}`);
    } catch (err) {
      console.error("Error submitting order:", err);
      alert(
        err instanceof Error
          ? `Failed to submit order: ${err.message}`
          : "Failed to submit order. Please try again."
      );
    } finally {
      setSubmitting(false);
    }
  };







  // Toggle tooltip visibility
  const toggleTooltip = (id: string | null) => {
    setShowTooltip(id);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-700">Loading...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="text-center text-red-600">
          <p>Error: {error}</p>
          <button
            className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            onClick={() => window.location.reload()}
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  // Get the current category
  const currentCategory = categories.find(cat => cat.id === selectedCategory);

  return (
    <div id="webcrumbs" className="container mx-auto py-8 px-4">
      <div className="bg-white p-6 rounded-lg shadow-lg lg:min-w-[1000px] max-w-[1200px] mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* First Column - Categories */}
          <div className="flex flex-col justify-between">
            <div>
              <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                <h2 className="font-bold">Start By Business category</h2>
              </div>

              <div className="space-y-2">
                {categories
                  .filter(cat => cat.status)
                  .sort((a, b) => a.sort_order - b.sort_order)
                  .map((category) => (
                    <div key={category.id} className="relative">
                      <label className="flex items-center">
                        <input
                          type="radio"
                          name="category"
                          className="w-4 h-4 text-primary-600 mr-2 accent-primary-600"
                          checked={selectedCategory === category.id}
                          onChange={() => handleCategoryChange(category.id)}
                        />
                        <span className="ml-1 flex items-center text-gray-700">
                          {category.id === selectedCategory && (
                            <span className="h-4 w-4 rounded-full bg-orange-500 mr-2"></span>
                          )}
                          {category.name}

                          {/* Question mark icon for categories with description */}
                          {category.description && (
                            <button
                              className="ml-2 text-gray-400 hover:text-gray-600 focus:outline-none"
                              onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                toggleTooltip(showTooltip === `category_${category.id}` ? null : `category_${category.id}`);
                              }}
                              onMouseEnter={() => toggleTooltip(`category_${category.id}`)}
                              onMouseLeave={() => toggleTooltip(null)}
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M12 21a9 9 0 100-18 9 9 0 000 18z" />
                              </svg>
                            </button>
                          )}
                        </span>
                      </label>

                      {/* Tooltip */}
                      {showTooltip === `category_${category.id}` && category.description && (
                        <div className="absolute left-8 top-6 z-10 w-64 p-3 bg-white border rounded-md shadow-lg text-sm text-gray-700">
                          {category.description}
                        </div>
                      )}
                    </div>
                  ))}
              </div>
            </div>

            <div className="mt-6">
              <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                <h2 className="font-bold">Description</h2>
              </div>

              <div className="text-sm space-y-3 text-gray-700">
                <p>
                  {currentCategory?.description ||
                    "Select the features you prefer to be available in your e-Business website."}
                </p>
                <p>
                  Primary Options are needed and we have to use pre-selected
                  items.
                </p>
                <p>
                  Secondary Options and More Options are by your choice and you
                  can select or deselect each feature that is listed.
                </p>
                <p>
                  Total amount of payment is calculated items prices and your
                  account credit balance amount.
                </p>
                <p>
                  Zero means your credit balance is more than your need and no
                  need to have any payment for this order.
                </p>
                <ul className="list-disc pl-6 space-y-1">
                  <li>Sum means sum of worth of items you selected.</li>
                  <li>
                    Account Credit balance means what will balance of you after
                    this order.
                  </li>
                </ul>
              </div>
            </div>
          </div>

          {/* Second Column - Options */}
          <div className="flex flex-col justify-between">
            {currentCategory && (
              <>
                {/* Primary Options */}
                <div>
                  <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                    <h2 className="font-bold">Primary Options</h2>
                  </div>

                  <div className="space-y-2">
                    {currentCategory.primary_options && Array.isArray(currentCategory.primary_options) &&
                      currentCategory.primary_options
                        .filter(option => option.status)
                        .sort((a, b) => a.sort_order - b.sort_order)
                        .map(option => (
                          <div key={option.id} className="relative">
                            <label className="flex items-center">
                              <input
                                type="checkbox"
                                className="w-4 h-4 text-primary-600 mr-2 accent-primary-600"
                                checked={!!selectedOptions[`primary_${option.id}`]}
                                onChange={() => handleOptionChange('primary', option.id)}
                                disabled={option.pivot.is_required === 1}
                              />
                              <span className="ml-1 text-gray-700 flex items-center">
                                {option.name} +${parseFloat(option.price.toString()).toFixed(2)}
                                {option.pivot.is_required === 1 && (
                                  <span className="ml-1 text-red-500 text-xs">(Required)</span>
                                )}

                                {/* Question mark icon for options with description */}
                                {option.description && (
                                  <button
                                    className="ml-2 text-gray-400 hover:text-gray-600 focus:outline-none"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      e.stopPropagation();
                                      toggleTooltip(showTooltip === `primary_${option.id}` ? null : `primary_${option.id}`);
                                    }}
                                    onMouseEnter={() => toggleTooltip(`primary_${option.id}`)}
                                    onMouseLeave={() => toggleTooltip(null)}
                                  >
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M12 21a9 9 0 100-18 9 9 0 000 18z" />
                                    </svg>
                                  </button>
                                )}
                              </span>
                            </label>

                            {/* Tooltip */}
                            {showTooltip === `primary_${option.id}` && option.description && (
                              <div className="absolute left-8 top-6 z-10 w-64 p-3 bg-white border rounded-md shadow-lg text-sm text-gray-700">
                                {option.description}
                              </div>
                            )}
                          </div>
                        ))
                    }
                    {(!currentCategory.primary_options || !Array.isArray(currentCategory.primary_options) || currentCategory.primary_options.length === 0) && (
                      <p className="text-gray-500">No primary options available for this category.</p>
                    )}
                  </div>
                </div>

                {/* Secondary Options */}
                <div className="mt-6">
                  <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                    <h2 className="font-bold">Secondary Options</h2>
                  </div>

                  <div className="space-y-2">
                    {currentCategory.secondary_options && Array.isArray(currentCategory.secondary_options) &&
                      currentCategory.secondary_options
                        .filter(option => option.status)
                        .sort((a, b) => a.sort_order - b.sort_order)
                        .map(option => (
                          <div key={option.id} className="relative">
                            <label className="flex items-center">
                              <input
                                type="checkbox"
                                className="w-4 h-4 text-primary-600 mr-2 accent-primary-600"
                                checked={!!selectedOptions[`secondary_${option.id}`]}
                                onChange={() => handleOptionChange('secondary', option.id)}
                                disabled={option.pivot.is_required === 1}
                              />
                              <span className="ml-1 text-gray-700 flex items-center">
                                {option.name} +${parseFloat(option.price.toString()).toFixed(2)}
                                {option.pivot.is_required === 1 && (
                                  <span className="ml-1 text-red-500 text-xs">(Required)</span>
                                )}

                                {/* Question mark icon for options with description */}
                                {option.description && (
                                  <button
                                    className="ml-2 text-gray-400 hover:text-gray-600 focus:outline-none"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      e.stopPropagation();
                                      toggleTooltip(showTooltip === `secondary_${option.id}` ? null : `secondary_${option.id}`);
                                    }}
                                    onMouseEnter={() => toggleTooltip(`secondary_${option.id}`)}
                                    onMouseLeave={() => toggleTooltip(null)}
                                  >
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M12 21a9 9 0 100-18 9 9 0 000 18z" />
                                    </svg>
                                  </button>
                                )}
                              </span>
                            </label>

                            {/* Tooltip */}
                            {showTooltip === `secondary_${option.id}` && option.description && (
                              <div className="absolute left-8 top-6 z-10 w-64 p-3 bg-white border rounded-md shadow-lg text-sm text-gray-700">
                                {option.description}
                              </div>
                            )}
                          </div>
                        ))
                    }
                    {(!currentCategory.secondary_options || !Array.isArray(currentCategory.secondary_options) || currentCategory.secondary_options.length === 0) && (
                      <p className="text-gray-500">No secondary options available for this category.</p>
                    )}
                  </div>
                </div>
              </>
            )}

            {/* Country Modules section */}
            <div className="mt-6">
              <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                <h2 className="font-bold">Please select your Country Modules</h2>
              </div>

              <div className="mb-4 text-sm text-gray-700">
                Your country <strong>{country}</strong> (your IP is detected)
                solutions are listed below. If it is not correct please choose
                your country.
              </div>

              <div className="relative mb-6">
                <select
                  className="w-full p-2 border border-gray-300 rounded appearance-none cursor-pointer hover:border-gray-400 transition duration-300 bg-white text-gray-700"
                  value={country}
                  onChange={handleCountryChange}
                >
                  {countryModules
                    .filter(module => module.is_active)
                    .map(module => module.country_name)
                    .filter((value, index, self) => self.indexOf(value) === index) // Remove duplicates
                    .map(countryName => (
                      <option key={countryName} value={countryName}>
                        {countryName}
                      </option>
                    ))
                  }
                  {countryModules.length === 0 && (
                    <option value="Belgium">Belgium</option>
                  )}
                </select>
                <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                  <svg
                    className="w-4 h-4 text-gray-500"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth="2"
                      d="M19 9l-7 7-7-7"
                    ></path>
                  </svg>
                </div>
              </div>

              {/* Display available modules for selected country */}
              <div className="space-y-2">
                {countryModules
                  .filter(module => module.country_name === country && module.is_active)
                  .map(module => (
                    <div key={module.id} className="p-2 border rounded bg-gray-50">
                      <div className="font-semibold">{module.module_name}</div>
                      <div className="text-sm text-gray-600">{module.description}</div>
                      <div className="text-right text-green-600 font-bold">+${parseFloat(module.price.toString()).toFixed(2)}</div>
                    </div>
                  ))
                }
                {countryModules.filter(module => module.country_name === country && module.is_active).length === 0 && (
                  <p className="text-gray-500">No modules available for this country.</p>
                )}
              </div>
            </div>
          </div>

          {/* Third Column - Sum and Submit (Sticky) */}
          <div className="lg:sticky lg:top-6 lg:self-start">
            <div className="bg-white p-4 rounded-lg shadow-md">
              <div className="bg-[#1c2e5a] text-white p-3 mb-4">
                <h2 className="font-bold text-right">Sum</h2>
              </div>

              <div className="text-right text-2xl font-bold text-green-700 mb-8">
                ${totalSum.toFixed(2)}
              </div>

              <button
                className={`w-full p-3 bg-green-500 text-white font-bold rounded hover:bg-green-600 transition duration-300 transform hover:scale-[1.01] ${submitting ? 'opacity-70 cursor-not-allowed' : ''}`}
                onClick={handleSubmit}
                disabled={submitting}
              >
                {submitting ? (
                  <div className="flex items-center justify-center">
                    <div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white mr-2"></div>
                    Processing...
                  </div>
                ) : (
                  "Submit"
                )}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
