/**
 * The services layer is organized as follows:
 *
 * - `services/utils.ts`: Core API utilities that handle authentication,
 *   request formatting, and common CRUD operations.
 *
 * - `services/[table]/query.ts`: Table-specific API methods that use the core utilities
 *   to interact with specific API endpoints. Each table has its own query file with
 *   specialized methods for that data type (e.g., courses, users, etc.).
 *
 * - `services/[table]/mock.ts`: Mock implementations of the same methods found in query.ts.
 *   These files serve as drop-in replacements for development or testing purposes.
 *
 * ## Mock Implementation
 *
 * The mock.ts files implement the EXACT SAME interface as their query.ts counterparts.
 * This means:
 *
 * - All method signatures are identical (same names, parameters, and return types)
 * - All exported types and interfaces are identical
 * - The mock implementations return realistic data structures that match what the API would return
 *
 * This allows for easy switching between real API calls and mock data by simply changing imports.
 */

"use client"

import { useEffect, useState } from "react"

export interface HelpCategory {
  id: number
  name: string
  description: string
  slug: string
  created_at: string
  updated_at: string
}

// Mock data for help categories
const mockHelpCategories: HelpCategory[] = [
  {
    id: 1,
    name: "Getting Started",
    description: "Basic information for new users",
    slug: "getting-started",
    created_at: "2023-01-15T08:30:00Z",
    updated_at: "2023-01-15T08:30:00Z",
  },
  {
    id: 2,
    name: "Account Management",
    description: "Managing your account settings and profile",
    slug: "account-management",
    created_at: "2023-01-16T10:15:00Z",
    updated_at: "2023-02-20T14:45:00Z",
  },
  {
    id: 3,
    name: "Courses and Enrollment",
    description: "Information about courses and how to enroll",
    slug: "courses-enrollment",
    created_at: "2023-01-18T09:45:00Z",
    updated_at: "2023-03-05T11:30:00Z",
  },
  {
    id: 4,
    name: "Payments and Billing",
    description: "Payment methods, invoices, and refunds",
    slug: "payments-billing",
    created_at: "2023-01-20T13:20:00Z",
    updated_at: "2023-01-20T13:20:00Z",
  },
  {
    id: 5,
    name: "Technical Support",
    description: "Technical issues and troubleshooting",
    slug: "technical-support",
    created_at: "2023-01-25T15:10:00Z",
    updated_at: "2024-04-10T09:15:00Z",
  },
]

// Mock data for help question answers
export interface HelpQuestionAnswer {
  id: number
  category_id: number
  question: string
  answer: string
  is_featured: boolean
  created_at: string
  updated_at: string
}

const mockHelpQuestionAnswers: HelpQuestionAnswer[] = [
  {
    id: 1,
    category_id: 1,
    question: "How do I create an account?",
    answer:
      "To create an account, click on the 'Sign Up' button in the top right corner of the homepage. Fill in your details and follow the instructions to complete the registration process.",
    is_featured: true,
    created_at: "2023-01-15T09:00:00Z",
    updated_at: "2023-01-15T09:00:00Z",
  },
  {
    id: 2,
    category_id: 1,
    question: "What are the system requirements?",
    answer:
      "Our platform works best on modern browsers like Chrome, Firefox, Safari, and Edge. Make sure your browser is updated to the latest version for the best experience.",
    is_featured: false,
    created_at: "2023-01-15T09:15:00Z",
    updated_at: "2023-01-15T09:15:00Z",
  },
  {
    id: 3,
    category_id: 2,
    question: "How do I change my password?",
    answer:
      "To change your password, go to your account settings, click on 'Security', and select 'Change Password'. You'll need to enter your current password and then your new password twice.",
    is_featured: true,
    created_at: "2023-01-16T10:30:00Z",
    updated_at: "2023-01-16T10:30:00Z",
  },
  {
    id: 4,
    category_id: 2,
    question: "Can I change my email address?",
    answer:
      "Yes, you can change your email address in your account settings. Go to 'Profile', click on 'Edit', and update your email address. You'll receive a verification email to confirm the change.",
    is_featured: false,
    created_at: "2023-01-16T10:45:00Z",
    updated_at: "2023-02-20T15:00:00Z",
  },
  {
    id: 5,
    category_id: 3,
    question: "How do I enroll in a course?",
    answer:
      "To enroll in a course, browse the course catalog, select the course you're interested in, and click the 'Enroll' button. Follow the payment instructions to complete your enrollment.",
    is_featured: true,
    created_at: "2023-01-18T10:00:00Z",
    updated_at: "2023-01-18T10:00:00Z",
  },
  {
    id: 6,
    category_id: 3,
    question: "Can I transfer to a different course?",
    answer:
      "Course transfers are possible within 7 days of enrollment. Contact our support team with your request, and they'll guide you through the process.",
    is_featured: false,
    created_at: "2023-01-18T10:15:00Z",
    updated_at: "2023-03-05T12:00:00Z",
  },
  {
    id: 7,
    category_id: 4,
    question: "What payment methods do you accept?",
    answer:
      "We accept credit/debit cards (Visa, Mastercard, American Express), PayPal, and bank transfers. All payments are processed securely through our payment gateway.",
    is_featured: true,
    created_at: "2023-01-20T13:30:00Z",
    updated_at: "2023-01-20T13:30:00Z",
  },
  {
    id: 8,
    category_id: 4,
    question: "How do I request a refund?",
    answer:
      "Refund requests must be submitted within 14 days of purchase. Go to your order history, select the order, and click 'Request Refund'. Our team will review your request within 3 business days.",
    is_featured: false,
    created_at: "2023-01-20T13:45:00Z",
    updated_at: "2023-01-20T13:45:00Z",
  },
  {
    id: 9,
    category_id: 5,
    question: "The video content isn't loading. What should I do?",
    answer:
      "If videos aren't loading, try refreshing the page, clearing your browser cache, or switching to a different browser. If the issue persists, check your internet connection and disable any ad blockers.",
    is_featured: true,
    created_at: "2023-01-25T15:30:00Z",
    updated_at: "2023-01-25T15:30:00Z",
  },
  {
    id: 10,
    category_id: 5,
    question: "How do I report a technical issue?",
    answer:
      "To report a technical issue, go to the Help Center and click on 'Report a Problem'. Provide as much detail as possible, including screenshots if applicable, to help our team resolve the issue quickly.",
    is_featured: false,
    created_at: "2023-01-25T15:45:00Z",
    updated_at: "2023-04-10T09:30:00Z",
  },
]

export function useHelpCategories() {
  const [categories, setCategories] = useState<HelpCategory[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        // Simulate API call
        await new Promise((resolve) => setTimeout(resolve, 800))
        setCategories(mockHelpCategories)
        setLoading(false)
      } catch (err) {
        setError(err instanceof Error ? err : new Error("Unknown error occurred"))
        setLoading(false)
      }
    }

    fetchCategories()
  }, [])

  return { categories, loading, error }
}

export function useHelpCategory(id: number) {
  const [category, setCategory] = useState<HelpCategory | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    const fetchCategory = async () => {
      try {
        // Simulate API call
        await new Promise((resolve) => setTimeout(resolve, 500))
        const foundCategory = mockHelpCategories.find((cat) => cat.id === id) || null
        setCategory(foundCategory)
        setLoading(false)
      } catch (err) {
        setError(err instanceof Error ? err : new Error("Unknown error occurred"))
        setLoading(false)
      }
    }

    fetchCategory()
  }, [id])

  return { category, loading, error }
}

export function useHelpQuestionAnswers(categoryId?: number) {
  const [questionAnswers, setQuestionAnswers] = useState<HelpQuestionAnswer[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    const fetchQuestionAnswers = async () => {
      try {
        // Simulate API call
        await new Promise((resolve) => setTimeout(resolve, 800))

        let filteredQAs = mockHelpQuestionAnswers
        if (categoryId) {
          filteredQAs = mockHelpQuestionAnswers.filter((qa) => qa.category_id === categoryId)
        }

        setQuestionAnswers(filteredQAs)
        setLoading(false)
      } catch (err) {
        setError(err instanceof Error ? err : new Error("Unknown error occurred"))
        setLoading(false)
      }
    }

    fetchQuestionAnswers()
  }, [categoryId])

  return { questionAnswers, loading, error }
}

export async function createHelpCategory(categoryData: Omit<HelpCategory, "id" | "created_at" | "updated_at">) {
  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 1000))

  // In a real implementation, this would be handled by the backend
  return {
    ...categoryData,
    id: Math.max(...mockHelpCategories.map((c) => c.id)) + 1,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
  }
}

export async function updateHelpCategory(
  id: number,
  categoryData: Partial<Omit<HelpCategory, "id" | "created_at" | "updated_at">>,
) {
  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 1000))

  // In a real implementation, this would be handled by the backend
  const category = mockHelpCategories.find((c) => c.id === id)
  if (!category) {
    throw new Error("Category not found")
  }

  return {
    ...category,
    ...categoryData,
    updated_at: new Date().toISOString(),
  }
}

export async function deleteHelpCategory(id: number) {
  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 1000))

  // In a real implementation, this would be handled by the backend
  const categoryIndex = mockHelpCategories.findIndex((c) => c.id === id)
  if (categoryIndex === -1) {
    throw new Error("Category not found")
  }

  return { success: true }
}

export default {
  useHelpCategories,
  useHelpCategory,
  useHelpQuestionAnswers,
  createHelpCategory,
  updateHelpCategory,
  deleteHelpCategory,
}
