import { useState, useEffect, useCallback } from "react";
import type {
  ImessageBridgeSettings,
  ImessageBridgeHealth,
  ImessageContact,
  ImessageHistoryMessage,
} from "@/lib/types";

export function useImessageBridge() {
  const [settings, setSettings] = useState<ImessageBridgeSettings | null>(null);
  const [health, setHealth] = useState<ImessageBridgeHealth | null>(null);
  const [contacts, setContacts] = useState<ImessageContact[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchAll = useCallback(async () => {
    try {
      const [settingsRes, healthRes, contactsRes] = await Promise.all([
        fetch("/api/admin/imessage/settings"),
        fetch("/api/admin/imessage/health"),
        fetch("/api/admin/imessage/contacts"),
      ]);
      if (settingsRes.ok) setSettings(await settingsRes.json());
      if (healthRes.ok) setHealth(await healthRes.json());
      if (contactsRes.ok) setContacts(await contactsRes.json());
    } catch {
      // Bridge offline
    } finally {
      setLoading(false);
    }
  }, []);

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

  const updateSettings = useCallback(
    async (updates: Partial<ImessageBridgeSettings>) => {
      const res = await fetch("/api/admin/imessage/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updates),
      });
      if (res.ok) {
        const data = await res.json();
        setSettings(data);
      }
    },
    []
  );

  const addContact = useCallback(
    async (name: string, identifier: string) => {
      const res = await fetch("/api/admin/imessage/contacts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, identifier }),
      });
      if (res.ok) {
        const contact = await res.json();
        setContacts((prev) => [...prev, contact]);
        return contact;
      }
    },
    []
  );

  const removeContact = useCallback(async (id: string) => {
    const res = await fetch(`/api/admin/imessage/contacts/${encodeURIComponent(id)}`, {
      method: "DELETE",
    });
    if (res.ok) {
      setContacts((prev) => prev.filter((c) => c.id !== id));
    }
  }, []);

  return {
    settings,
    health,
    contacts,
    loading,
    updateSettings,
    addContact,
    removeContact,
    refresh: fetchAll,
  };
}

export function useImessageHistory(contact?: string) {
  const [messages, setMessages] = useState<ImessageHistoryMessage[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchHistory = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (contact) params.set("contact", contact);
      const res = await fetch(`/api/admin/imessage/history?${params}`);
      if (res.ok) {
        setMessages(await res.json());
      }
    } catch {
      // Bridge offline
    } finally {
      setLoading(false);
    }
  }, [contact]);

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

  return { messages, loading, refresh: fetchHistory };
}
