"use client";

import { useState, useEffect, useCallback } from "react";
import {
  getPreferences,
  savePreferences,
  getUsageData,
  saveUsageEntry,
  getWeeklyData,
  calculateWeeklyAverage,
  generateQuitPlan as generateQuitPlanFn,
  hasOneWeekOfData,
  fetchPreferences,
  fetchUsageData,
  UserPreferences,
  UsageEntry,
  QuitPlan,
} from "@/lib/storage";
import { getTodayString } from "@/lib/date-utils";

type SubstanceType = 'nicotine' | 'weed';

interface UserData {
  substanceType: SubstanceType;
  stayLoggedIn: boolean;
  onboardingComplete: boolean;
}

export function useUserData() {
  const [userData, setUserData] = useState<UserData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const loadData = async () => {
      const prefs = await fetchPreferences();
      setUserData({
        substanceType: prefs.substance,
        stayLoggedIn: true,
        onboardingComplete: prefs.hasCompletedSetup,
      });
      setIsLoading(false);
    };
    loadData();
  }, []);

  const updateUserData = useCallback((data: Partial<UserData>) => {
    const prefs = getPreferences();
    const updated: UserPreferences = {
      ...prefs,
      substance: data.substanceType || prefs.substance,
      hasCompletedSetup: data.onboardingComplete ?? prefs.hasCompletedSetup,
    };
    savePreferences(updated);
    setUserData((prev) => (prev ? { ...prev, ...data } : null));
    return updated;
  }, []);

  const completeOnboarding = useCallback(
    (substanceType: SubstanceType, _stayLoggedIn: boolean) => {
      return updateUserData({
        substanceType,
        stayLoggedIn: true,
        onboardingComplete: true,
      });
    },
    [updateUserData]
  );

  return {
    userData,
    isLoading,
    updateUserData,
    completeOnboarding,
    isOnboardingComplete: userData?.onboardingComplete ?? false,
  };
}

export function useUsageLogs() {
  const [logs, setLogs] = useState<UsageEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const refreshLogs = useCallback(async () => {
    const data = await fetchUsageData();
    setLogs(data);
  }, []);

  useEffect(() => {
    refreshLogs().then(() => setIsLoading(false));
  }, [refreshLogs]);

  const logUsage = useCallback(
    (puffs: number, date?: string) => {
      const prefs = getPreferences();
      const logDate = date || getTodayString();
      const newEntry: UsageEntry = {
        date: logDate,
        count: puffs,
        substance: prefs.substance,
      };
      saveUsageEntry(newEntry);
      refreshLogs();
      return newEntry;
    },
    [refreshLogs]
  );

  const getRecent = useCallback((days: number = 7) => {
    const data = getUsageData();
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);
    return data.filter((e) => new Date(e.date) >= cutoff);
  }, []);

  const calculateStats = (entries: UsageEntry[]) => {
    if (entries.length === 0) {
      return { totalPuffs: 0, averagePuffs: 0, daysTracked: 0 };
    }
    const totalPuffs = entries.reduce((sum, e) => sum + e.count, 0);
    const daysTracked = new Set(entries.map((e) => e.date)).size;
    const averagePuffs = Math.round(totalPuffs / daysTracked);
    return { totalPuffs, averagePuffs, daysTracked };
  };

  const stats = calculateStats(getRecent(7));

  return {
    logs,
    isLoading,
    logUsage,
    getRecent,
    refreshLogs,
    stats,
  };
}

export function useQuitPlan() {
  const [plan, setPlan] = useState<QuitPlan | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const refreshPlan = useCallback(async () => {
    const prefs = await fetchPreferences();
    setPlan(prefs.quitPlan);
  }, []);

  useEffect(() => {
    refreshPlan().then(() => setIsLoading(false));
  }, [refreshPlan]);

  const createPlan = useCallback(() => {
    const prefs = getPreferences();
    const avgPuffs = calculateWeeklyAverage(prefs.substance);

    if (avgPuffs === 0) {
      return null;
    }

    const newPlan = generateQuitPlanFn(prefs.substance);
    const updatedPrefs = { ...prefs, quitPlan: newPlan };
    savePreferences(updatedPrefs);
    setPlan(newPlan);
    return newPlan;
  }, []);

  const getCurrentWeek = (quitPlan: QuitPlan): number => {
    const startDate = new Date(quitPlan.startDate);
    const today = new Date();
    const weekNumber = Math.floor(
      (today.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 7)
    );
    return Math.min(weekNumber, quitPlan.weeklyTargets.length - 1);
  };

  const currentWeek = plan ? getCurrentWeek(plan) : 0;
  const prefs = getPreferences();
  const canGenerate = hasOneWeekOfData(prefs.substance);
  const weeklyData = getWeeklyData(prefs.substance);
  const daysTracked = new Set(weeklyData.map((e) => e.date)).size;

  return {
    plan,
    isLoading,
    createPlan,
    refreshPlan,
    currentWeek,
    canGenerate,
    daysTracked,
  };
}

export function useCheckIn() {
  const [needsCheckIn, setNeedsCheckIn] = useState(false);

  useEffect(() => {
    // Check if user needs to check in today
    const today = new Date().toISOString().split("T")[0];
    const data = getUsageData();
    const todayEntry = data.find((e) => e.date === today);
    setNeedsCheckIn(!todayEntry);
  }, []);

  const markCheckedIn = useCallback(() => {
    setNeedsCheckIn(false);
  }, []);

  return {
    needsCheckIn,
    markCheckedIn,
  };
}
