import { AxiosError } from "axios";
import { apiClient } from "../../app/api/client";
import { handleAPIError } from "../utils/apiErrorHandler";

export interface FormFieldOption {
  id: string;
  name: string;
  fullData?: any;  

  /////extra
  image?: string;
  ageRange?: string;
  duration?: string;
  time?: string;
}

export interface FormField {
  rows: number | null;
  text: string | null;
  type: string;
  field: string;
  checked: boolean;
  options: string[] | FormFieldOption[];
  required: boolean;
  is_global: boolean;
  placeholder: string | null;
}

export interface FormStep {
  id: string;
  order: number;
  fields: FormField[];
  heading: string;
  subheading: string;
  main_heading?: string;
  main_subheading?: string;
}

export interface FormFields {
  cta?: {
    text: string;
    type: string;
    field: string;
    required: boolean;
    is_global: boolean;
  };
  agree?: {
    text: string;
    type: string;
    field: string;
    required: boolean;
    is_global: boolean;
  };
  steps?: FormStep[];
}

export interface Form {
  id: string;
  franchisee_id: string;
  parent_form_id: string;
  name: string;
  fields: FormFields;
  language: string;
  translated: boolean;
  description?: string;
  status: string;
  is_global: boolean;
  created_at: string;
  updated_at: string;
  form_setting: {
    form_cc?: string;
    send_to?: string;
    from_name?: string;
    from_email?: string;
    form_message?: string;
    form_subject?: string;
    success_message?: string;
    featured_image?: string;
  };
  deleted_at?: string;
  pages?: string[];
}

export interface FormsResponse {
  status: boolean;
  message: string;
  data: Form[];
}

export class FormsService {
  private readonly endpoint = "forms/home";

  async fetchByDomain(domain: string, franchiseeId?: string | null, language?: string | null, page: string = "home"): Promise<Form | null> {
    const startTime = Date.now();

    try {
      const params: Record<string, string> = {};
      if (franchiseeId) {
        params.franchiseeId = franchiseeId;
      }
      if (language && language !== "default") {
        params.lang = language;
      }

      const response = await apiClient.get<FormsResponse>(
        `forms/${page}`,
        {
          headers: { "X-Domain": domain },
          params: Object.keys(params).length > 0 ? params : undefined,
        }
      );

      if (!response.data?.status || !Array.isArray(response.data?.data)) {
        return null;
      }
   
      // Take the first form for this page — deliberately WITHOUT re-checking
      // status. The backend already scopes it to the domain: DetectTenantContext
      // sets status='draft' for preview.youngengineers.org and 'publish'
      // otherwise, and FormController::getAllForms filters translations on that
      // before echoing the real value back in `status`.
      //
      // Re-filtering on "Published" here therefore threw away every form the
      // preview domain returned (they all come back as "Draft"), which is why
      // preview rendered no form while every other section worked — forms were
      // the only content type applying a second, client-side status filter.
      const form = response.data.data.find((f) => f.pages?.includes(page));

      if (!form) {
        return null;
      }

      const elapsed = Date.now() - startTime;

      return form;
    } catch (error) {
      // Delegate error handling to reusable utility
      const elapsed = Date.now() - startTime;
      return handleAPIError(
        error,
        domain,
        startTime,
        () => null
      );
    }
  }
}

export const formsService = new FormsService();