"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import {
  X,
  Phone,
  Clock,
  User,
  Bot,
  AlertCircle,
  Plus,
  Download,
  Calendar,
} from "lucide-react";
import logger from "@/lib/logger";
import type {
  VoiceConversationDetail,
  VoiceTranscriptMessage,
  VoiceAction,
} from "@/lib/types/voice-agent-staff.types";

interface VoiceTranscriptModalProps {
  conversationId: string | null;
  isOpen: boolean;
  onClose: () => void;
  onOpenCreateAction?: (conversationId: string) => void;
}

const actionStatusColors: Record<string, string> = {
  PENDING: "bg-yellow-100 text-yellow-800 border-yellow-200",
  IN_PROGRESS: "bg-blue-100 text-blue-800 border-blue-200",
  COMPLETED: "bg-green-100 text-green-800 border-green-200",
  DISMISSED: "bg-gray-100 text-gray-600 border-gray-200",
};

const actionTypeColors: Record<string, string> = {
  CALL_BACK: "bg-purple-100 text-purple-700",
  SEND_EMAIL: "bg-blue-100 text-blue-700",
  BOOK_APPOINTMENT: "bg-green-100 text-green-700",
  ESCALATE: "bg-red-100 text-red-700",
  CUSTOM: "bg-gray-100 text-gray-700",
};

function formatDuration(seconds: number): string {
  if (seconds < 60) {
    return `${Math.round(seconds)} seconds`;
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.round(seconds % 60);
  return remainingSeconds > 0
    ? `${minutes}m ${remainingSeconds}s`
    : `${minutes} minutes`;
}

function formatDateTime(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleString("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function formatTime(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

function MessageBubble({ message }: { message: VoiceTranscriptMessage }) {
  const isAI = message.sender === "AI";

  return (
    <div className={`flex ${isAI ? "justify-end" : "justify-start"}`}>
      <div
        className={`max-w-[75%] rounded-2xl px-4 py-3 ${
          isAI
            ? "bg-blue-600 text-white rounded-br-sm"
            : "bg-gray-100 text-gray-900 rounded-bl-sm"
        }`}
      >
        <div className="flex items-center gap-2 mb-1">
          {isAI ? <Bot className="w-4 h-4" /> : <User className="w-4 h-4" />}
          <span
            className={`text-xs font-medium ${isAI ? "text-blue-100" : "text-gray-500"}`}
          >
            {isAI ? "AI Agent" : "Customer"}
          </span>
        </div>
        <p className="text-sm whitespace-pre-wrap break-words">
          {message.content}
        </p>
        <p
          className={`text-xs mt-1 ${isAI ? "text-blue-200" : "text-gray-400"}`}
        >
          {formatTime(message.timestamp)}
        </p>
      </div>
    </div>
  );
}

function ActionCard({ action }: { action: VoiceAction }) {
  return (
    <div
      className={`border rounded-lg p-3 ${actionStatusColors[action.status]}`}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span
              className={`px-2 py-0.5 rounded text-xs font-medium ${
                actionTypeColors[action.type] || "bg-gray-100 text-gray-700"
              }`}
            >
              {action.type.replace("_", " ")}
            </span>
            <span className="text-xs font-medium uppercase">
              {action.status}
            </span>
          </div>
          <p className="font-medium text-sm truncate">{action.title}</p>
          {action.description && (
            <p className="text-xs text-gray-600 mt-1 line-clamp-2">
              {action.description}
            </p>
          )}
          {action.dueAt && (
            <p className="text-xs text-gray-500 mt-1 flex items-center gap-1">
              <Calendar className="w-3 h-3" />
              Due: {new Date(action.dueAt).toLocaleDateString()}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

export default function VoiceTranscriptModal({
  conversationId,
  isOpen,
  onClose,
  onOpenCreateAction,
}: VoiceTranscriptModalProps) {
  const [conversation, setConversation] =
    useState<VoiceConversationDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const fetchConversation = useCallback(async () => {
    if (!conversationId) return;

    try {
      setLoading(true);
      setError(null);

      const response = await fetch(
        `/api/staff/voice-agents/conversations/${conversationId}`,
      );

      if (!response.ok) {
        if (response.status === 404) {
          throw new Error("Conversation not found");
        }
        throw new Error("Failed to fetch conversation");
      }

      const data = await response.json();
      setConversation(data.conversation);
    } catch (err) {
      logger.error("Failed to fetch conversation", {
        error: err,
        conversationId,
      });
      setError(
        err instanceof Error ? err.message : "Failed to load conversation",
      );
    } finally {
      setLoading(false);
    }
  }, [conversationId]);

  useEffect(() => {
    if (isOpen && conversationId) {
      fetchConversation();
    }
  }, [isOpen, conversationId, fetchConversation]);

  // Scroll to bottom when transcript loads
  useEffect(() => {
    if (conversation?.transcript.length) {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [conversation?.transcript]);

  // Close on Escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    if (isOpen) {
      window.addEventListener("keydown", handleEscape);
      return () => window.removeEventListener("keydown", handleEscape);
    }
  }, [isOpen, onClose]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = "";
      };
    }
  }, [isOpen]);

  const handleExportJSON = () => {
    if (!conversation) return;
    const exportData = JSON.stringify(conversation, null, 2);
    const blob = new Blob([exportData], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `voice-conversation-${conversation.id}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleAddAction = () => {
    if (conversationId && onOpenCreateAction) {
      onOpenCreateAction(conversationId);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl h-[85vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
              <Phone className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              {loading ? (
                <div className="space-y-2">
                  <div className="h-5 bg-gray-200 rounded w-32 animate-pulse" />
                  <div className="h-4 bg-gray-200 rounded w-48 animate-pulse" />
                </div>
              ) : conversation ? (
                <>
                  <h3 className="text-lg font-bold text-gray-900">
                    {conversation.customerName || "Unknown Customer"}
                  </h3>
                  <div className="flex items-center gap-3 text-sm text-gray-600">
                    {conversation.customerPhone && (
                      <span>{conversation.customerPhone}</span>
                    )}
                    <span className="flex items-center gap-1">
                      <Clock className="w-3.5 h-3.5" />
                      {formatDuration(conversation.duration)}
                    </span>
                    <span className="text-gray-400">|</span>
                    <span>{formatDateTime(conversation.createdAt)}</span>
                  </div>
                </>
              ) : (
                <h3 className="text-lg font-bold text-gray-900">
                  Conversation Details
                </h3>
              )}
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-gray-100 transition"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* Content */}
        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600 mx-auto" />
              <p className="mt-4 text-gray-600">Loading conversation...</p>
            </div>
          </div>
        ) : error ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center">
              <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
              <h4 className="text-lg font-medium text-red-900 mb-2">Error</h4>
              <p className="text-red-600 mb-4">{error}</p>
              <button
                onClick={fetchConversation}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
              >
                Try Again
              </button>
            </div>
          </div>
        ) : conversation ? (
          <div className="flex-1 flex overflow-hidden">
            {/* Transcript Section */}
            <div className="flex-1 flex flex-col overflow-hidden border-r border-gray-200">
              <div className="px-4 py-2 bg-gray-50 border-b border-gray-200">
                <h4 className="text-sm font-medium text-gray-700">
                  Transcript ({conversation.transcript.length} messages)
                </h4>
              </div>
              <div className="flex-1 overflow-y-auto p-4 space-y-3 bg-gray-50">
                {conversation.transcript.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">
                    <Phone className="w-10 h-10 mx-auto mb-2 text-gray-300" />
                    <p>No transcript available</p>
                  </div>
                ) : (
                  <>
                    {conversation.transcript.map((message) => (
                      <MessageBubble key={message.id} message={message} />
                    ))}
                    <div ref={messagesEndRef} />
                  </>
                )}
              </div>
            </div>

            {/* Actions Section */}
            <div className="w-80 flex flex-col overflow-hidden">
              <div className="px-4 py-2 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                <h4 className="text-sm font-medium text-gray-700">
                  Actions ({conversation.actions.length})
                </h4>
                <button
                  onClick={handleAddAction}
                  className="flex items-center gap-1 px-2 py-1 text-xs font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded transition"
                >
                  <Plus className="w-3.5 h-3.5" />
                  Add
                </button>
              </div>
              <div className="flex-1 overflow-y-auto p-3 space-y-2">
                {conversation.actions.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">
                    <AlertCircle className="w-10 h-10 mx-auto mb-2 text-gray-300" />
                    <p className="text-sm">No actions yet</p>
                    <button
                      onClick={handleAddAction}
                      className="mt-2 text-sm text-blue-600 hover:text-blue-700"
                    >
                      Create one
                    </button>
                  </div>
                ) : (
                  conversation.actions.map((action) => (
                    <ActionCard key={action.id} action={action} />
                  ))
                )}
              </div>
            </div>
          </div>
        ) : null}

        {/* Footer */}
        <div className="p-4 border-t border-gray-200 flex items-center justify-between">
          <div className="text-sm text-gray-500">
            {conversation && <span>ID: {conversation.id.slice(-12)}</span>}
          </div>
          <div className="flex gap-2">
            <button
              onClick={handleExportJSON}
              disabled={!conversation}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Download className="w-4 h-4" />
              Export JSON
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
