import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL, createQueryKey } from '../client';
import type { FiscalYear } from '@/types/periods';

// GraphQL Queries
const FISCAL_YEARS_QUERY = gql`
  query FiscalYears($companyId: ID!) {
    fiscalYears(companyId: $companyId) {
      id
      companyId
      name
      startDate
      endDate
      status
      openingBalancePosted
      closingDate
      closedBy
      reopenedDate
      reopenedBy
      lockedDate
      lockedBy
      createdAt
      updatedAt
    }
  }
`;

const FISCAL_YEAR_QUERY = gql`
  query FiscalYear($id: ID!) {
    fiscalYear(id: $id) {
      id
      companyId
      name
      startDate
      endDate
      status
      openingBalancePosted
      closingDate
      closedBy
      reopenedDate
      reopenedBy
      lockedDate
      lockedBy
      createdAt
      updatedAt
    }
  }
`;

// Response types
interface FiscalYearResponse {
  id: string;
  companyId: string;
  name: string;
  startDate: string;
  endDate: string;
  status: string;
  openingBalancePosted: boolean;
  closingDate?: string;
  closedBy?: string;
  reopenedDate?: string;
  reopenedBy?: string;
  lockedDate?: string;
  lockedBy?: string;
  createdAt: string;
  updatedAt: string;
}

interface FiscalYearsQueryResponse {
  fiscalYears: FiscalYearResponse[];
}

interface FiscalYearQueryResponse {
  fiscalYear: FiscalYearResponse | null;
}

// Transform backend response to frontend type
function transformFiscalYear(fy: FiscalYearResponse): FiscalYear {
  return {
    id: fy.id,
    companyId: fy.companyId,
    name: fy.name,
    startDate: fy.startDate,
    endDate: fy.endDate,
    status: fy.status.toLowerCase() as 'open' | 'closed' | 'locked',
    openingBalancePosted: fy.openingBalancePosted,
    closingDate: fy.closingDate,
    closedBy: fy.closedBy,
    reopenedDate: fy.reopenedDate,
    reopenedBy: fy.reopenedBy,
    lockedDate: fy.lockedDate,
    lockedBy: fy.lockedBy,
    createdAt: fy.createdAt,
    updatedAt: fy.updatedAt,
  };
}

/**
 * Hook to fetch all fiscal years for a company.
 */
export function useFiscalYears(
  companyId: string | undefined,
  options?: Omit<UseQueryOptions<FiscalYear[], Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('fiscalYears', { companyId }),
    queryFn: async () => {
      if (!companyId) return [];
      const data = await fetchGraphQL<FiscalYearsQueryResponse>(FISCAL_YEARS_QUERY, {
        companyId,
      });
      return data.fiscalYears.map(transformFiscalYear);
    },
    enabled: !!companyId,
    ...options,
  });
}

/**
 * Hook to fetch a single fiscal year by ID.
 */
export function useFiscalYear(
  id: string | undefined,
  options?: Omit<UseQueryOptions<FiscalYear | null, Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('fiscalYear', { id }),
    queryFn: async () => {
      if (!id) return null;
      const data = await fetchGraphQL<FiscalYearQueryResponse>(FISCAL_YEAR_QUERY, { id });
      return data.fiscalYear ? transformFiscalYear(data.fiscalYear) : null;
    },
    enabled: !!id,
    ...options,
  });
}
