"use client";

import { useState, useEffect, useRef } from "react";
import type { Lang } from "@/lib/config";
import { X, Loader2, Phone, Clock, User, Bot } from "lucide-react";

interface TranscriptEntry {
  speaker: "user" | "agent";
  text: string;
  timestamp: string;
}

interface ConversationData {
  id: string;
  customerPhone?: string;
  customerName?: string;
  status: string;
  duration?: number;
  outcome?: string;
  sentiment?: string;
  transcript: TranscriptEntry[];
  createdAt: string;
  actions?: Array<{ type: string; description: string }>;
}

interface CallTranscriptModalProps {
  lang: Lang;
  conversationId: string;
  isOpen: boolean;
  onClose: () => void;
}

function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, "0")}`;
}

function formatTimestamp(ts: string): string {
  try {
    return new Date(ts).toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return ts;
  }
}

export default function CallTranscriptModal({
  lang,
  conversationId,
  isOpen,
  onClose,
}: CallTranscriptModalProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [conversation, setConversation] = useState<ConversationData | null>(
    null,
  );
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen || !conversationId) return;

    setLoading(true);
    setError(null);

    fetch(`/api/voice-agent/conversations/${conversationId}`)
      .then((res) => {
        if (!res.ok) throw new Error("Failed to load conversation");
        return res.json();
      })
      .then((data: { success: boolean; conversation: ConversationData }) => {
        if (data.success && data.conversation) {
          setConversation(data.conversation);
        } else {
          throw new Error("Invalid conversation data");
        }
      })
      .catch((err: Error) => {
        setError(err.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [isOpen, conversationId]);

  useEffect(() => {
    if (!loading && scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [loading, conversation]);

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

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/40 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-2xl max-h-[85vh] bg-white rounded-2xl shadow-2xl border border-slate-200 flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-brand-green/10 flex items-center justify-center">
              <Phone className="w-5 h-5 text-brand-green" />
            </div>
            <div>
              <h3 className="font-semibold text-slate-900">
                {conversation?.customerPhone ||
                  (isAr ? "محادثة" : "Conversation")}
              </h3>
              <div className="flex items-center gap-3 text-xs text-slate-500">
                {conversation?.createdAt && (
                  <span>
                    {new Date(conversation.createdAt).toLocaleDateString(
                      isAr ? "ar-QA" : "en-US",
                      {
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )}
                  </span>
                )}
                {conversation?.duration != null && (
                  <span className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {formatDuration(conversation.duration)}
                  </span>
                )}
                {conversation?.sentiment && (
                  <span className="px-2 py-0.5 rounded-full bg-slate-100 capitalize">
                    {conversation.sentiment}
                  </span>
                )}
              </div>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-xl hover:bg-slate-100 transition-colors"
            aria-label={isAr ? "إغلاق" : "Close"}
          >
            <X className="w-5 h-5 text-slate-500" />
          </button>
        </div>

        {/* Body */}
        <div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-4">
          {loading && (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-8 h-8 animate-spin text-brand-green" />
              <span className="ml-3 text-slate-500">
                {isAr ? "جاري التحميل..." : "Loading transcript..."}
              </span>
            </div>
          )}

          {error && (
            <div className="text-center py-20">
              <p className="text-red-500 text-sm">{error}</p>
              <button
                onClick={onClose}
                className="mt-4 px-4 py-2 text-sm bg-slate-100 hover:bg-slate-200 rounded-xl text-slate-700 transition-colors"
              >
                {isAr ? "إغلاق" : "Close"}
              </button>
            </div>
          )}

          {!loading && !error && conversation?.transcript?.length === 0 && (
            <div className="text-center py-20 text-slate-400">
              {isAr ? "لا يوجد نص محادثة" : "No transcript available"}
            </div>
          )}

          {!loading &&
            !error &&
            conversation?.transcript?.map((entry, idx) => {
              const isAgent = entry.speaker === "agent";
              return (
                <div
                  key={idx}
                  className={`flex gap-3 ${isAgent ? "justify-start" : "justify-end"}`}
                >
                  {isAgent && (
                    <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center flex-shrink-0 mt-1">
                      <Bot className="w-4 h-4 text-slate-600" />
                    </div>
                  )}
                  <div
                    className={`max-w-[75%] rounded-2xl px-4 py-3 ${
                      isAgent
                        ? "bg-slate-100 text-slate-800"
                        : "bg-brand-green/10 text-slate-800"
                    }`}
                  >
                    <p className="text-sm leading-relaxed">{entry.text}</p>
                    <p className="text-[10px] text-slate-400 mt-1">
                      {formatTimestamp(entry.timestamp)}
                    </p>
                  </div>
                  {!isAgent && (
                    <div className="w-8 h-8 rounded-full bg-brand-green/20 flex items-center justify-center flex-shrink-0 mt-1">
                      <User className="w-4 h-4 text-brand-green" />
                    </div>
                  )}
                </div>
              );
            })}
        </div>

        {/* Footer with actions */}
        {conversation?.actions && conversation.actions.length > 0 && (
          <div className="border-t border-slate-100 p-4">
            <p className="text-xs font-medium text-slate-500 mb-2">
              {isAr ? "الإجراءات المتخذة" : "Actions Taken"}
            </p>
            <div className="flex flex-wrap gap-2">
              {conversation.actions.map((action, idx) => (
                <span
                  key={idx}
                  className="inline-flex items-center px-3 py-1 rounded-full bg-blue-50 text-blue-700 text-xs font-medium"
                >
                  {action.description}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
