import React from 'react';
import Container from '../../components/atoms/Container';
import VisitvisaCompanyInfo from '../../components/molecules/VisitvisaCompanyInfo';
import AllVisaDestination from '../../components/organisms/AllVisaDestinations';
import Client from '../../components/molecules/Client';
import VisaApply from '../../components/molecules/VisaApply';
import OurOffice from '../../components/molecules/OurOffices';

export const metadata = {
  title: "Expert Study Visa & Visit Visa Consultant | Universities Page",
  description: "Apply for your student visa or visit visa with expert guidance. We ensure hassle-free processing and provide complete support to make your travel dreams a reality.",
  siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
  type: "website",
  alternates: {
    canonical: `${process.env.NEXT_PUBLIC_APP_URL}/visit-visa`,
  },
  openGraph: {
    title: "Expert Study Visa & Visit Visa Consultant | Universities Page",
    description: "Apply for your student visa or visit visa with expert guidance. We ensure hassle-free processing and provide complete support to make your travel dreams a reality.",
    url: `${process.env.NEXT_PUBLIC_APP_URL}/visit-visa`,
    siteName: process.env.NEXT_PUBLIC_APP_WEBSITE_NAME,
    type: "website",
  },
  twitter: {
    card: "summary_large_image",
    title: "Expert Study Visa & Visit Visa Consultant | Universities Page",
    description: "Apply for your student visa or visit visa with expert guidance. We ensure hassle-free processing and provide complete support to make your travel dreams a reality.",
  },
  robots: {
    index: true,
    follow: true,
    nocache: false,
    googleBot: {
      index: true,
      follow: true,
      noimageindex: false,
      "max-video-preview": -1,
      "max-image-preview": "large",
      "max-snippet": -1,
    },
  },
};

interface VisaCountry {
  id: number;
  country_name: string;
  country_image?: string;
  banner_image?: string;
  continent: string;
  currency: string;
  price: number;
  discount_price?: number;
  slug: string;
  visa_types: string[];
  popularity?: number;
}

const getAllCountries = async (): Promise<any[]> => {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/visa-country?limit=1000`, {
      next: { revalidate: 3600 }
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch: ${response.status}`);
    }

    const result = await response.json();

    if (!result.success || !Array.isArray(result.data)) {
      throw new Error('Invalid data format received');
    }

    return result.data.map((country: VisaCountry) => ({
      id: country.id,
      name: country.country_name,
      flag: country.country_image || '/assets/default-flag.png',
      banner: country.banner_image,
      continent: country.continent,
      actual: `${country.currency} ${country.price}`,
      discounted: country.discount_price
        ? `${country.currency} ${country.discount_price}`
        : null,
      discount:
        country.price > 0 && country.discount_price > 0
          ? `${Math.round(
              ((parseFloat(country.price.toString()) -
                parseFloat(country.discount_price?.toString() || '0')) /
                parseFloat(country.price.toString())) *
                100
            )}% OFF`
          : null,
      slug: country.slug,
      visaTypes: country.visa_types,
      link: `/visit-visa/${country.slug}`,
      popularity: country.popularity || Math.random() * 100,
    }));
  } catch (error) {
    console.error('Error fetching countries:', error);
    return [];
  }
};

const VisitVisa = async () => { // Remove searchParams from props
  // Fetch data on the server
  const allCountries = await getAllCountries();

  return (
    <div className="bg-linear-to-b from-gray-50 to-white">
      <VisitvisaCompanyInfo/>
      <Container>
        <div className="py-16 space-y-20">
          <AllVisaDestination allCountries={allCountries} />
          <VisaApply/>
          <Client/>
          <OurOffice/>
        </div>
      </Container>
    </div>
  );
};

export default VisitVisa;