import { useState, useEffect, useCallback } from 'react';
import supportPlanService, { 
  type SupportPlan, 
  type SupportPlanListParams, 
  type CreateSupportPlanData 
} from '../services/supportPlanService';

// Hook for fetching support plan list
export const useSupportPlanList = (params: SupportPlanListParams = {}) => {
  const [supportPlans, setSupportPlans] = useState<SupportPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalCount, setTotalCount] = useState(0);

  const fetchSupportPlans = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      // Fetch list
      const response = await supportPlanService.getSupportPlans(params);
      setSupportPlans(response.data);

      // Fetch count separately for accurate pagination
      const countResponse = await fetch('/api/method/frappe.client.get_count', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          doctype: 'Support Plans',
          filters: params.filters || {}
        })
      });
      const countData = await countResponse.json();
      setTotalCount(countData.message || response.data.length);

    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch support plans');
      setSupportPlans([]);
    } finally {
      setLoading(false);
    }
  }, [
    params.filters, 
    params.limit_start, 
    params.limit_page_length, 
    params.order_by
  ]);

  useEffect(() => {
    fetchSupportPlans();
  }, [fetchSupportPlans]);

  return {
    supportPlans,
    loading,
    error,
    totalCount,
    refetch: fetchSupportPlans
  };
};

// Hook for fetching single support plan details
export const useSupportPlanDetails = (name: string | null) => {
  const [supportPlan, setSupportPlan] = useState<SupportPlan | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchSupportPlan = useCallback(async () => {
    if (!name) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const data = await supportPlanService.getSupportPlan(name);
      setSupportPlan(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch support plan');
      setSupportPlan(null);
    } finally {
      setLoading(false);
    }
  }, [name]);

  useEffect(() => {
    fetchSupportPlan();
  }, [fetchSupportPlan]);

  return {
    supportPlan,
    loading,
    error,
    refetch: fetchSupportPlan
  };
};

// Hook for support plan mutations (create, update, delete)
export const useSupportPlanMutations = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const createSupportPlan = useCallback(async (data: CreateSupportPlanData): Promise<SupportPlan> => {
    try {
      setLoading(true);
      setError(null);
      const result = await supportPlanService.createSupportPlan(data);
      return result;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to create support plan';
      setError(message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updateSupportPlan = useCallback(async (
    name: string, 
    data: Partial<CreateSupportPlanData>
  ): Promise<SupportPlan> => {
    try {
      setLoading(true);
      setError(null);
      const result = await supportPlanService.updateSupportPlan(name, data);
      return result;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to update support plan';
      setError(message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteSupportPlan = useCallback(async (name: string): Promise<void> => {
    try {
      setLoading(true);
      setError(null);
      await supportPlanService.deleteSupportPlan(name);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to delete support plan';
      setError(message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    createSupportPlan,
    updateSupportPlan,
    deleteSupportPlan,
    loading,
    error
  };
};

export default {
  useSupportPlanList,
  useSupportPlanDetails,
  useSupportPlanMutations
};