"use client";

import { useEffect, useRef } from "react";
import { MessageCircle } from "lucide-react";
import { useImessageHistory } from "@/hooks/useImessageBridge";
import type { ImessageHistoryMessage } from "@/lib/types";

function formatTime(ts: number): string {
  return new Date(ts * 1000).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  });
}

function ImessageMessage({ msg }: { msg: ImessageHistoryMessage }) {
  const isInbound = msg.direction === "inbound";
  return (
    <div className={`flex ${isInbound ? "justify-start" : "justify-end"}`}>
      <div
        className={`max-w-[75%] rounded-2xl px-4 py-2 ${
          isInbound
            ? "bg-zinc-100 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-100"
            : "bg-blue-500 text-white"
        }`}
      >
        <p className="text-sm whitespace-pre-wrap">{msg.text}</p>
        <p
          className={`mt-1 text-xs ${
            isInbound
              ? "text-zinc-400 dark:text-zinc-500"
              : "text-blue-100"
          }`}
        >
          {formatTime(msg.timestamp)}
        </p>
      </div>
    </div>
  );
}

interface ImessageHistoryProps {
  refreshInterval?: number;
}

export function ImessageHistory({ refreshInterval = 10000 }: ImessageHistoryProps) {
  const { messages, loading, refresh } = useImessageHistory();
  const bottomRef = useRef<HTMLDivElement>(null);

  // Auto-refresh
  useEffect(() => {
    const id = setInterval(refresh, refreshInterval);
    return () => clearInterval(id);
  }, [refresh, refreshInterval]);

  // Auto-scroll
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-sm text-zinc-400">Loading iMessage history...</p>
      </div>
    );
  }

  if (messages.length === 0) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-3">
        <MessageCircle size={32} className="text-zinc-300 dark:text-zinc-600" />
        <p className="text-sm text-zinc-400 dark:text-zinc-500">
          No iMessage conversations yet
        </p>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      <div className="flex-1 overflow-y-auto px-4 py-4">
        <div className="mx-auto max-w-2xl space-y-3">
          {messages.map((msg) => (
            <ImessageMessage key={msg.id} msg={msg} />
          ))}
          <div ref={bottomRef} />
        </div>
      </div>
    </div>
  );
}
