import { useState, useEffect, useCallback } from 'react';
import inspectionService, { 
  type Inspection, 
  type InspectionListParams, 
  type CreateInspectionData,
} from '../services/inspectionService';

interface UseInspectionListResult {
  inspections: Inspection[];
  loading: boolean;
  error: string | null;
  totalCount: number;
  refetch: () => void;
}

interface UseInspectionDetailsResult {
  inspection: Inspection | null;
  loading: boolean;
  error: string | null;
  refetch: () => void;
}

interface UseInspectionMutationsResult {
  createInspection: (data: CreateInspectionData) => Promise<Inspection>;
  updateInspection: (name: string, data: Partial<CreateInspectionData>) => Promise<Inspection>;
  deleteInspection: (name: string) => Promise<void>;
  loading: boolean;
  error: string | null;
}

// Hook for fetching inspection list
export function useInspectionList(params: InspectionListParams = {}): UseInspectionListResult {
  const [inspections, setInspections] = useState<Inspection[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalCount, setTotalCount] = useState(0);

  const paramsKey = JSON.stringify(params);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        setLoading(true);
        setError(null);
        const [listResponse, count] = await Promise.all([
          inspectionService.getInspections(params),
          inspectionService.getInspectionCount(params.filters || {}),
        ]);
        if (cancelled) return;
        setInspections(listResponse.data);
        setTotalCount(count);
      } catch (err) {
        if (cancelled) return;
        const errorMessage = err instanceof Error ? err.message : 'Failed to fetch inspections';
        setError(errorMessage);
        console.error('Error fetching inspections:', err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [paramsKey]);

  const refetch = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const [listResponse, count] = await Promise.all([
        inspectionService.getInspections(params),
        inspectionService.getInspectionCount(params.filters || {}),
      ]);
      setInspections(listResponse.data);
      setTotalCount(count);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch inspections';
      setError(errorMessage);
      console.error('Error fetching inspections:', err);
    } finally {
      setLoading(false);
    }
  }, [paramsKey]);

  return {
    inspections,
    loading,
    error,
    totalCount,
    refetch,
  };
}

// Hook for fetching single inspection details
export function useInspectionDetails(name: string | null): UseInspectionDetailsResult {
  const [inspection, setInspection] = useState<Inspection | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

    try {
      setLoading(true);
      setError(null);
      const data = await inspectionService.getInspection(name);
      setInspection(data);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch inspection';
      setError(errorMessage);
      console.error('Error fetching inspection:', err);
    } finally {
      setLoading(false);
    }
  }, [name]);

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

  return {
    inspection,
    loading,
    error,
    refetch: fetchInspection
  };
}

// Hook for inspection mutations (create, update, delete)
export function useInspectionMutations(): UseInspectionMutationsResult {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const createInspection = async (data: CreateInspectionData): Promise<Inspection> => {
    try {
      setLoading(true);
      setError(null);
      const result = await inspectionService.createInspection(data);
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to create inspection';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const updateInspection = async (name: string, data: Partial<CreateInspectionData>): Promise<Inspection> => {
    try {
      setLoading(true);
      setError(null);
      const result = await inspectionService.updateInspection(name, data);
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to update inspection';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteInspection = async (name: string): Promise<void> => {
    try {
      setLoading(true);
      setError(null);
      await inspectionService.deleteInspection(name);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to delete inspection';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return {
    createInspection,
    updateInspection,
    deleteInspection,
    loading,
    error
  };
}