"use client";

import { useCallback, useEffect, useState } from "react";
import { useWorkspaceStore } from "@/stores/workspace-store";
import type {
  AutomationActionConfig,
  AutomationActionType,
  AutomationRule,
  AutomationRuleConditions,
  AutomationRun,
  AutomationScheduleFrequency,
  AutomationStep,
  AutomationTriggerMode,
  WebhookEventType,
} from "@/types";

interface CreateAutomationInput {
  name: string;
  description?: string;
  triggerMode: AutomationTriggerMode;
  triggerEvent?: WebhookEventType;
  scheduleFrequency?: AutomationScheduleFrequency | null;
  scheduleTime?: string | null;
  scheduleDayOfWeek?: number | null;
  scheduleTimezone?: string | null;
  conditions: AutomationRuleConditions;
  actionType?: AutomationActionType;
  actionConfig?: AutomationActionConfig;
  steps: AutomationStep[];
  isActive?: boolean;
}

export function useAutomations() {
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);
  const [rules, setRules] = useState<AutomationRule[]>([]);
  const [runs, setRuns] = useState<AutomationRun[]>([]);
  const [loading, setLoading] = useState(true);

  const teamQuery = activeTeamId ? `?teamId=${encodeURIComponent(activeTeamId)}` : "";

  const fetchAll = useCallback(async () => {
    if (!initialized) return;

    setLoading(true);
    const res = await fetch(`/api/automations${teamQuery}`);
    const json = res.ok ? await res.json() : { rules: [], runs: [] };

    setRules(json.rules || []);
    setRuns(json.runs || []);
    setLoading(false);
  }, [initialized, teamQuery]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void fetchAll();
    }, 0);

    return () => window.clearTimeout(timer);
  }, [fetchAll]);

  async function createAutomation(input: CreateAutomationInput) {
    const res = await fetch("/api/automations", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        teamId: activeTeamId,
        name: input.name,
        description: input.description || "",
        triggerMode: input.triggerMode,
        triggerEvent: input.triggerEvent,
        scheduleFrequency: input.scheduleFrequency,
        scheduleTime: input.scheduleTime,
        scheduleDayOfWeek: input.scheduleDayOfWeek,
        scheduleTimezone: input.scheduleTimezone,
        conditions: input.conditions,
        actionType: input.actionType,
        actionConfig: input.actionConfig,
        steps: input.steps,
        isActive: input.isActive !== false,
      }),
    });

    const json = await res.json();
    if (!res.ok) {
      throw new Error(json.error || "Automation could not be created");
    }

    setRules((prev) => [json.rule, ...prev]);
    return json.rule as AutomationRule;
  }

  async function updateAutomation(
    id: string,
    input: Partial<{
      name: string;
      description: string;
      triggerMode: AutomationTriggerMode;
      triggerEvent: WebhookEventType;
      scheduleFrequency: AutomationScheduleFrequency | null;
      scheduleTime: string | null;
      scheduleDayOfWeek: number | null;
      scheduleTimezone: string | null;
      conditions: AutomationRuleConditions;
      actionType: AutomationActionType;
      actionConfig: AutomationActionConfig;
      steps: AutomationStep[];
      isActive: boolean;
    }>
  ) {
    const res = await fetch(`/api/automations/${id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(input),
    });

    const json = await res.json();
    if (!res.ok) {
      throw new Error(json.error || "Automation could not be updated");
    }

    setRules((prev) => prev.map((rule) => (rule.id === id ? json.rule : rule)));
    return json.rule as AutomationRule;
  }

  async function deleteAutomation(id: string) {
    const res = await fetch(`/api/automations/${id}`, {
      method: "DELETE",
    });

    const json = await res.json();
    if (!res.ok) {
      throw new Error(json.error || "Automation could not be deleted");
    }

    setRules((prev) => prev.filter((rule) => rule.id !== id));
    setRuns((prev) => prev.filter((run) => run.rule_id !== id));
  }

  return {
    activeTeamId,
    rules,
    runs,
    loading,
    createAutomation,
    updateAutomation,
    deleteAutomation,
    refetch: fetchAll,
  };
}
