"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Search,
  Phone,
  Clock,
  ChevronLeft,
  ChevronRight,
  AlertCircle,
  Calendar,
  X,
} from "lucide-react";
import logger from "@/lib/logger";
import type { VoiceConversationSummary } from "@/lib/types/voice-agent-staff.types";

interface VoiceConversationsListProps {
  agentId?: string;
  onConversationSelect: (id: string) => void;
}

const statusColors: Record<string, string> = {
  open: "bg-green-100 text-green-800",
  closed: "bg-gray-100 text-gray-600",
  archived: "bg-yellow-100 text-yellow-800",
};

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

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

export default function VoiceConversationsList({
  agentId,
  onConversationSelect,
}: VoiceConversationsListProps) {
  const [conversations, setConversations] = useState<
    VoiceConversationSummary[]
  >([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [search, setSearch] = useState("");
  const [status, setStatus] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");

  // Pagination
  const [limit] = useState(20);
  const [offset, setOffset] = useState(0);

  const fetchConversations = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (agentId) params.append("agentId", agentId);
      if (search) params.append("search", search);
      if (status) params.append("status", status);
      if (dateFrom) params.append("dateFrom", new Date(dateFrom).toISOString());
      if (dateTo) params.append("dateTo", new Date(dateTo).toISOString());
      params.append("limit", String(limit));
      params.append("offset", String(offset));

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

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

      const data = await response.json();
      setConversations(data.conversations);
      setTotal(data.total);
    } catch (err) {
      logger.error("Failed to fetch conversations", { error: err });
      setError("Failed to load conversations. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [agentId, search, status, dateFrom, dateTo, limit, offset]);

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

  // Reset pagination when filters change
  useEffect(() => {
    setOffset(0);
  }, [agentId, search, status, dateFrom, dateTo]);

  const clearFilters = () => {
    setSearch("");
    setStatus("");
    setDateFrom("");
    setDateTo("");
    setOffset(0);
  };

  const hasFilters = search || status || dateFrom || dateTo;
  const totalPages = Math.ceil(total / limit);
  const currentPage = Math.floor(offset / limit) + 1;

  // Loading state
  if (loading && conversations.length === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="p-4 border-b border-gray-200 space-y-3">
          <div className="h-10 bg-gray-200 rounded-lg animate-pulse" />
          <div className="flex gap-2">
            <div className="h-10 bg-gray-200 rounded-lg animate-pulse flex-1" />
            <div className="h-10 bg-gray-200 rounded-lg animate-pulse flex-1" />
          </div>
        </div>
        <div className="divide-y divide-gray-200">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="p-4 space-y-2">
              <div className="h-4 bg-gray-200 rounded w-1/3 animate-pulse" />
              <div className="h-3 bg-gray-200 rounded w-1/2 animate-pulse" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-red-200 p-8 text-center">
        <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-red-900 mb-2">
          Error Loading Conversations
        </h3>
        <p className="text-red-600 mb-4">{error}</p>
        <button
          onClick={fetchConversations}
          className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
        >
          Try Again
        </button>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      {/* Filters */}
      <div className="p-4 border-b border-gray-200 space-y-3">
        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search by customer name or phone..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
          />
        </div>

        {/* Filter Row */}
        <div className="flex flex-wrap gap-2">
          {/* Status Filter */}
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">All Statuses</option>
            <option value="open">Open</option>
            <option value="closed">Closed</option>
            <option value="archived">Archived</option>
          </select>

          {/* Date From */}
          <div className="relative">
            <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="date"
              value={dateFrom}
              onChange={(e) => setDateFrom(e.target.value)}
              placeholder="From date"
              className="pl-10 pr-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Date To */}
          <div className="relative">
            <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="date"
              value={dateTo}
              onChange={(e) => setDateTo(e.target.value)}
              placeholder="To date"
              className="pl-10 pr-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Clear Filters */}
          {hasFilters && (
            <button
              onClick={clearFilters}
              className="flex items-center gap-1.5 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
            >
              <X className="w-4 h-4" />
              Clear
            </button>
          )}
        </div>
      </div>

      {/* Table Header */}
      <div className="hidden md:grid grid-cols-12 gap-4 px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
        <div className="col-span-3">Customer</div>
        <div className="col-span-2 text-center">Duration</div>
        <div className="col-span-3">Date/Time</div>
        <div className="col-span-2 text-center">Status</div>
        <div className="col-span-2 text-center">Actions</div>
      </div>

      {/* Conversations List */}
      <div className="divide-y divide-gray-200">
        {conversations.length === 0 ? (
          <div className="p-12 text-center">
            <Phone className="w-12 h-12 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              No Conversations
            </h3>
            <p className="text-gray-600">
              {hasFilters
                ? "No conversations match your filters."
                : "No voice conversations have been recorded yet."}
            </p>
          </div>
        ) : (
          conversations.map((conversation) => (
            <button
              key={conversation.id}
              onClick={() => onConversationSelect(conversation.id)}
              className="w-full text-left px-4 py-4 hover:bg-gray-50 transition-colors"
            >
              {/* Mobile Layout */}
              <div className="md:hidden space-y-2">
                <div className="flex items-center justify-between">
                  <span className="font-medium text-gray-900">
                    {conversation.customerName ||
                      conversation.customerPhone ||
                      "Unknown"}
                  </span>
                  <span
                    className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                      statusColors[conversation.status] ||
                      "bg-gray-100 text-gray-600"
                    }`}
                  >
                    {conversation.status}
                  </span>
                </div>
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {formatDuration(conversation.duration)}
                  </span>
                  <span>{formatDateTime(conversation.createdAt)}</span>
                  {conversation.actionsCount > 0 && (
                    <span className="flex items-center gap-1 text-orange-600">
                      <AlertCircle className="w-3 h-3" />
                      {conversation.actionsCount}
                    </span>
                  )}
                </div>
              </div>

              {/* Desktop Layout */}
              <div className="hidden md:grid grid-cols-12 gap-4 items-center">
                <div className="col-span-3">
                  <p className="font-medium text-gray-900 truncate">
                    {conversation.customerName || "Unknown"}
                  </p>
                  {conversation.customerPhone && (
                    <p className="text-xs text-gray-500">
                      {conversation.customerPhone}
                    </p>
                  )}
                </div>
                <div className="col-span-2 text-center">
                  <span className="inline-flex items-center gap-1 text-sm text-gray-700">
                    <Clock className="w-3.5 h-3.5" />
                    {formatDuration(conversation.duration)}
                  </span>
                </div>
                <div className="col-span-3">
                  <span className="text-sm text-gray-600">
                    {formatDateTime(conversation.createdAt)}
                  </span>
                </div>
                <div className="col-span-2 text-center">
                  <span
                    className={`px-2.5 py-1 rounded-full text-xs font-medium ${
                      statusColors[conversation.status] ||
                      "bg-gray-100 text-gray-600"
                    }`}
                  >
                    {conversation.status}
                  </span>
                </div>
                <div className="col-span-2 text-center">
                  {conversation.actionsCount > 0 ? (
                    <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-orange-100 text-orange-700 text-xs font-medium">
                      <AlertCircle className="w-3 h-3" />
                      {conversation.actionsCount} pending
                    </span>
                  ) : (
                    <span className="text-sm text-gray-400">-</span>
                  )}
                </div>
              </div>
            </button>
          ))
        )}
      </div>

      {/* Pagination */}
      {total > limit && (
        <div className="px-4 py-3 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
          <p className="text-sm text-gray-600">
            Showing {offset + 1}-{Math.min(offset + limit, total)} of {total}
          </p>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setOffset(Math.max(0, offset - limit))}
              disabled={offset === 0}
              className="p-2 rounded-lg border border-gray-300 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed transition"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            <span className="text-sm text-gray-600">
              Page {currentPage} of {totalPages}
            </span>
            <button
              onClick={() => setOffset(offset + limit)}
              disabled={offset + limit >= total}
              className="p-2 rounded-lg border border-gray-300 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed transition"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Refresh indicator */}
      {loading && conversations.length > 0 && (
        <div className="absolute inset-0 bg-white/50 flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
        </div>
      )}
    </div>
  );
}
