"use client";

import React, { useEffect, useState } from "react";
import DeleteConfirmDialog from "./DeleteConfirmDialog";
import {
  AlertCircle,
  Clock3,
  Loader2,
  MessageSquareText,
  RefreshCw,
  Trash2,
} from "lucide-react";

export interface Thread {
  _id?: string;
  id?: string;
  thread_id?: string;
  user_id: string;
  title?: string;
  created_at: string;
  updated_at?: string;
  messages?: {
    question?: string;
    response?: string;
  }[];
  message_count?: number;
}

interface Props {
  userId: string;
  authToken?: string | null;
  onSelectThread: (threadId: string) => void;
  onDeleteThread: (threadId: string) => void;
  currentThreadId?: string;
}

export default function ChatHistory({
  userId,
  authToken,
  onSelectThread,
  onDeleteThread,
  currentThreadId,
}: Props) {
  const [threads, setThreads] = useState<Thread[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    threadId: string;
    threadTitle: string;
    isDeleting: boolean;
  }>({
    isOpen: false,
    threadId: "",
    threadTitle: "",
    isDeleting: false,
  });

  useEffect(() => {
    fetchThreads();
  }, [userId]);

  const authHeaders = (): Record<string, string> => ({
    ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
  });

  const fetchThreads = async () => {
    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch(`/api/threads?user_id=${userId}&limit=20`, {
        method: "GET",
        headers: authHeaders(),
      });

      if (!response.ok) {
        throw new Error("Failed to fetch threads");
      }

      const data = await response.json();
      setThreads(data.threads || []);
    } catch (err) {
      console.error("Error fetching threads:", err);
      setError("Failed to load history");
    } finally {
      setIsLoading(false);
    }
  };

  const handleDelete = async (threadId: string, e: React.MouseEvent) => {
    e.stopPropagation();

    const thread = threads.find((t) => {
      const tId = t._id || t.id || t.thread_id;
      return tId === threadId;
    });

    const threadTitle = thread ? getThreadPreview(thread) : "Conversation";

    setDeleteConfirm({
      isOpen: true,
      threadId,
      threadTitle,
      isDeleting: false,
    });
  };

  const handleConfirmDelete = async () => {
    const { threadId } = deleteConfirm;

    setDeleteConfirm((prev) => ({ ...prev, isDeleting: true }));

    try {
      const response = await fetch(
        `/api/threads/${threadId}?user_id=${userId}`,
        {
          method: "DELETE",
          headers: authHeaders(),
        },
      );

      if (!response.ok) {
        throw new Error("Failed to delete thread");
      }

      setThreads((prev) =>
        prev.filter((t) => {
          const tId = t._id || t.id || t.thread_id;
          return tId !== threadId;
        }),
      );

      onDeleteThread(threadId);

      setDeleteConfirm({
        isOpen: false,
        threadId: "",
        threadTitle: "",
        isDeleting: false,
      });
    } catch (err) {
      console.error("Error deleting thread:", err);
      setError("Failed to delete conversation");
      setDeleteConfirm((prev) => ({ ...prev, isDeleting: false }));
    }
  };

  const handleCancelDelete = () => {
    setDeleteConfirm({
      isOpen: false,
      threadId: "",
      threadTitle: "",
      isDeleting: false,
    });
  };

  const getThreadPreview = (thread: Thread): string => {
    if (thread.title && thread.title.trim() !== "") {
      return thread.title;
    }

    if (thread.messages && thread.messages.length > 0) {
      const firstMessage = thread.messages[0];
      return firstMessage.question || firstMessage.response || "Conversation";
    }

    if (thread.message_count && thread.message_count > 0) {
      return "Conversation";
    }

    return "New conversation";
  };

  const getThreadDate = (dateString: string): string => {
    // Relies on the backend returning a properly timezone-tagged ISO string
    // (e.g. via datetime.now(timezone.utc).isoformat(), which appends
    // "+00:00") — see aicommand's models.py. A marker-less string here would
    // be ambiguous (we can't safely guess the server's clock/timezone from
    // the frontend) and should be treated as a backend bug, not patched
    // around here.
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return "now";
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    if (diffDays < 7) return `${diffDays}d ago`;

    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
    });
  };

  return (
    <div className="flex h-full flex-col bg-white">
      <div className="border-b bg-slate-50 px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <div>
            <p className="text-sm font-semibold text-slate-800">
              Recent conversations
            </p>
            <p className="text-xs text-slate-500">
              Pick a thread to continue where you left off
            </p>
          </div>

          <button
            onClick={fetchThreads}
            disabled={isLoading}
            className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-60"
            title="Refresh history"
          >
            <RefreshCw
              className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
            />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-2 py-2 history-scrollbar">
        {isLoading ? (
          <div className="flex h-full min-h-[240px] items-center justify-center">
            <div className="text-center">
              <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 shadow-sm">
                <Loader2 className="h-4 w-4 animate-spin text-blue-600" />
                <span className="text-sm font-medium text-slate-600">
                  Loading history...
                </span>
              </div>
            </div>
          </div>
        ) : error ? (
          <div className="flex h-full min-h-[240px] items-center justify-center px-4">
            <div className="max-w-xs rounded-2xl border border-red-200 bg-red-50 px-4 py-4 text-center shadow-sm">
              <div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-red-100">
                <AlertCircle className="h-5 w-5 text-red-600" />
              </div>
              <p className="text-sm font-medium text-red-800">{error}</p>
              <button
                onClick={fetchThreads}
                className="mt-3 inline-flex items-center gap-1 rounded-full bg-white px-3 py-1.5 text-xs font-medium text-red-700 ring-1 ring-red-200 transition hover:bg-red-100"
              >
                <RefreshCw className="h-3.5 w-3.5" />
                Retry
              </button>
            </div>
          </div>
        ) : threads.length === 0 ? (
          <div className="flex h-full min-h-[240px] items-center justify-center px-4">
            <div className="max-w-xs text-center">
              <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-100">
                <MessageSquareText className="h-5 w-5 text-slate-500" />
              </div>
              <p className="text-sm font-medium text-slate-700">
                No conversations yet
              </p>
              <p className="mt-1 text-xs leading-5 text-slate-500">
                Once you start chatting, your recent conversations will appear
                here.
              </p>
            </div>
          </div>
        ) : (
          <div className="space-y-2">
            {threads.map((thread) => {
              const threadId =
                thread._id || thread.id || thread.thread_id || "";
              const isActive = currentThreadId === threadId;

              return (
                <button
                  key={threadId}
                  onClick={() => onSelectThread(threadId)}
                  className={`group w-full rounded-xl border px-1 py-1 text-left transition-all ${
                    isActive
                      ? "border-blue-200 bg-blue-50 shadow-sm"
                      : "border-slate-200 bg-white hover:border-blue-200 hover:bg-slate-50"
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div
                      className={`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${
                        isActive
                          ? "bg-blue-100 text-blue-700"
                          : "bg-slate-100 text-slate-500"
                      }`}
                    >
                      <MessageSquareText className="h-4 w-4" />
                    </div>

                    <div className="min-w-0 flex-1">
                      <p
                        className={`line-clamp-2 text-sm font-medium leading-5 ${
                          isActive ? "text-blue-900" : "text-slate-800"
                        }`}
                      >
                        {getThreadPreview(thread)}
                      </p>

                      <div className="mt-2 flex items-center gap-2 text-[11px] text-slate-500">
                        <Clock3 className="h-3.5 w-3.5" />
                        <span>{getThreadDate(thread.updated_at || thread.created_at)}</span>
                      </div>
                    </div>

                    <button
                      onClick={(e) => handleDelete(threadId, e)}
                      className="mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-red-500 transition hover:bg-red-50 hover:text-red-600 md:opacity-0 md:group-hover:opacity-100"
                      title="Delete conversation"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      <DeleteConfirmDialog
        isOpen={deleteConfirm.isOpen}
        threadTitle={deleteConfirm.threadTitle}
        isDeleting={deleteConfirm.isDeleting}
        onConfirm={handleConfirmDelete}
        onCancel={handleCancelDelete}
      />
    </div>
  );
}
