import { useState, useEffect, useCallback } from 'react';
import { Dimensions, ScaledSize } from 'react-native';

export interface ResponsiveState {
  width: number;
  height: number;
  isPhone: boolean;
  isTablet: boolean;
  isDesktop: boolean;
  isLargeDesktop: boolean;
  isPortrait: boolean;
  isLandscape: boolean;
  gutter: number;
  contentPadding: number;
  cardColumns: number;
  fontSize: {
    h1: number;
    h2: number;
    h3: number;
    body: number;
    bodySmall: number;
    caption: number;
    stat: number;
  };
}

function computeBreakpoints(width: number, height: number): ResponsiveState {
  const isPhone = width < 640;
  const isTablet = width >= 640 && width < 1024;
  const isDesktop = width >= 1024 && width < 1440;
  const isLargeDesktop = width >= 1440;

  let gutter: number;
  let contentPadding: number;
  let cardColumns: number;

  if (isPhone) {
    gutter = 8;
    contentPadding = 12;
    cardColumns = 1;
  } else if (isTablet) {
    gutter = 12;
    contentPadding = 16;
    cardColumns = 2;
  } else if (isDesktop) {
    gutter = 16;
    contentPadding = 24;
    cardColumns = 2;
  } else {
    gutter = 20;
    contentPadding = 32;
    cardColumns = 4;
  }

  const fontScale = isPhone ? 0.9 : isTablet ? 0.95 : 1;

  return {
    width,
    height,
    isPhone,
    isTablet,
    isDesktop,
    isLargeDesktop,
    isPortrait: height > width,
    isLandscape: width > height,
    gutter,
    contentPadding,
    cardColumns,
    fontSize: {
      h1: Math.round(30 * fontScale),
      h2: Math.round(24 * fontScale),
      h3: Math.round(20 * fontScale),
      body: Math.round(15 * fontScale),
      bodySmall: Math.round(13 * fontScale),
      caption: Math.round(12 * fontScale),
      stat: Math.round(28 * fontScale),
    },
  };
}

export function useResponsive(): ResponsiveState {
  const [state, setState] = useState<ResponsiveState>(() => {
    const { width, height } = Dimensions.get('window');
    return computeBreakpoints(width, height);
  });

  useEffect(() => {
    const onChange = ({ window }: { window: ScaledSize }) => {
      setState(computeBreakpoints(window.width, window.height));
    };
    const sub = Dimensions.addEventListener('change', onChange);
    return () => sub?.remove();
  }, []);

  return state;
}

export function useIsPhone(): boolean {
  const [isPhone, setIsPhone] = useState(() => Dimensions.get('window').width < 640);
  useEffect(() => {
    const sub = Dimensions.addEventListener('change', ({ window }) => {
      setIsPhone(window.width < 640);
    });
    return () => sub?.remove();
  }, []);
  return isPhone;
}
