import axios, { AxiosError } from "axios";

const CLASSWISE_API_URL = process.env.NEXT_PUBLIC_CLASSWISE_API_URL || "https://backend.classwise.youngengineers.org/api/v3";
const CLASSWISE_TOKEN = process.env.CLASSWISE_TOKEN || "";

export interface ClasswiseProgram {
  id: number;
  name: string;
  slug: string;
  title: string;
  program_code: string;
  image: string;
  header_image: string;
  status: number;
  order: number;
  totalLessons: number;
}

export interface ClasswiseLocation {
  id: number;
  name: string;
  location: string;
  country: string;
  country_code: string;
  status: string;
  latlng?: string;
}

export interface ClasswiseInstructor {
  id: number;
  name: string;
}

export interface ClasswiseClass {
  id: string | number;
  group_name: string;
  min_age: number;
  max_age: number;
  start_date: string;
  start_time: string;
  end_time: string;
  frequency: string;
  day: string[];
  status: string;
  totalStudents: number;
  totalLessons: number;
  next_lesson_date: string;
  pos_id: number;
  program_id: number;
  value?: string | number;
  currency?: any;
  latlng?: string;
  p_o_s: ClasswiseLocation;
  program: ClasswiseProgram;
  instructor_list: ClasswiseInstructor[];
  is_demo?: boolean;
  payment_charges_frequency?: string;
  fee_basis?: string;
}

export interface ClasswiseClassesResponse {
  status: string;
  message: string;
  data: ClasswiseClass[];
  total: number;
  totalPage: number;
  currentPage: number;
  perPage: number;
}

// Separate axios instance for Classwise API
const classwiseApiClient = axios.create({
  baseURL: CLASSWISE_API_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": CLASSWISE_TOKEN,
  },
});

export class ClasswiseClassesService {
  // Static demo class
  // private getDemoClass(): ClasswiseClass {
  //   return {
  //     id: "demo-001",
  //     group_name: "Free Demo Class",
  //     min_age: 6,
  //     max_age: 12,
  //     start_date: new Date().toISOString().split('T')[0],
  //     start_time: "09:00 AM",
  //     end_time: "10:00 AM",
  //     frequency: "weekly",
  //     day: ["Saturday"],
  //     status: "active",
  //     totalStudents: 0,
  //     totalLessons: 1,
  //     next_lesson_date: new Date().toISOString().split('T')[0],
  //     pos_id: 323,
  //     program_id: 2,
  //     value: "0",
  //     currency: {
  //       id: 6,
  //       country_currency_id: 47,
  //       currency: "Rupees",
  //       symbol: "₹",
  //       code: "INR"
  //     },
  //     latlng: "31.541576492618706,76.25496787590949",
  //     p_o_s: {
  //       id: 323,
  //       name: "POS 1",
  //       location: "G7R3+JX Nangal Salangri, Himachal Pradesh, India",
  //       country: "India",
  //       country_code: "IN",
  //       status: "active"
  //     },
  //     program: {
  //       id: 2,
  //       name: "Demo",
  //       slug: "free-demo",
  //       title: "Free Demo Class",
  //       program_code: "DEMO",
  //       image: "https://classwise.s3.eu-central-1.amazonaws.com/media/build_programs/1757326505.Camps.png",
  //       header_image: "https://classwise.s3.eu-central-1.amazonaws.com/media/build_programs/1757326505.Camps.png",
  //       status: 1,
  //       order: 99,
  //       totalLessons: 1
  //     },
  //     instructor_list: [
  //       {
  //         id: 1,
  //         name: "Demo Instructor"
  //       }
  //     ],
  //     is_demo: true
  //   };
  // }

  async fetchClasses(
    accountId?: string,
    franchiseeId?: string | null,
    programIds?: Array<string | number>
  ): Promise<ClasswiseClass[]> {
    const startTime = Date.now();
    const resolvedAccountId = accountId

    try {
      const response = await classwiseApiClient.get<ClasswiseClassesResponse>(
        "/get-group-list",
        {
          params: {
            account_id: resolvedAccountId,
            franchiseeId: franchiseeId || undefined,
            program_id: programIds && programIds.length > 0 ? programIds : undefined,
          },
          // Backend expects program_id[]=22&program_id[]=23 (Laravel bracket form).
          // Build query string manually so brackets stay literal and arrays repeat correctly.
          paramsSerializer: (p: Record<string, any>) => {
            const out: string[] = [];
            Object.keys(p).forEach((key) => {
              const val = p[key];
              if (val === undefined || val === null) return;
              if (Array.isArray(val)) {
                val.forEach((v) => out.push(`${encodeURIComponent(key)}[]=${encodeURIComponent(String(v))}`));
              } else {
                out.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`);
              }
            });
            return out.join("&");
          },
        }
      );

      if (!response.data?.status || response.data.status !== "success") {
        return [];
      }

      if (!Array.isArray(response.data?.data)) {
        return [];
      }

      const elapsed = Date.now() - startTime;

      // Add demo class at the beginning of the array
      // const demoClass = this.getDemoClass();
      return response.data.data;
    } catch (error) {
      const elapsed = Date.now() - startTime;
      console.error(
        `[ClasswiseClassesService] ✗ Failed to fetch classes in ${elapsed}ms:`,
        error instanceof AxiosError ? error.message : error
      );
      return [];
    }
  }
}

export const classwiseClassesService = new ClasswiseClassesService();

export interface PaymentPlan {
  id: number;
  student_id: number | null;
  group_id: number;
  status: string;
  due_date: string;
  received_date: string | null;
  amount: string;
  payment_method: string;
  payment_link: string | null;
  is_user_added: number;
  created_at: string;
  updated_at: string;
}

export interface PaymentPlansResponse {
  status: string;
  message: string;
  error_type: string;
  data: PaymentPlan[];
}

export class ClasswisePaymentPlansService {
  async fetchPaymentPlans(groupId: string | number, accountId: string, franchiseeId?: string | null): Promise<PaymentPlan[]> {
    try {
      const response = await classwiseApiClient.get<PaymentPlansResponse>(
        "/get-group-payment-plans",
        {
          params: {
            group_id: groupId,
            account_id: accountId,
            franchiseeId: franchiseeId || undefined,
          },
        }
      );

      if (response.data?.status !== "success" || !Array.isArray(response.data?.data)) {
        return [];
      }

      return response.data.data;
    } catch (error) {
      console.error("[ClasswisePaymentPlansService] ✗ Failed to fetch payment plans:", error);
      return [];
    }
  }
}

export const classwisePaymentPlansService = new ClasswisePaymentPlansService();
