"use client";

import { useState } from "react";
import { Search, Phone, Clock, User, ChevronRight } from "lucide-react";
import type { VoiceAgentSummary } from "@/lib/types/voice-agent-staff.types";

interface VoiceAgentsListProps {
  agents: VoiceAgentSummary[];
  onAgentSelect: (agentId: string) => void;
  selectedAgentId?: string;
}

function formatDate(dateString: string | null): string {
  if (!dateString) return "Never";
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));

  if (diffHours < 1) {
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    return diffMinutes <= 1 ? "Just now" : `${diffMinutes}m ago`;
  }
  if (diffHours < 24) {
    return `${diffHours}h ago`;
  }
  if (diffHours < 48) {
    return "Yesterday";
  }
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

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

export default function VoiceAgentsList({
  agents,
  onAgentSelect,
  selectedAgentId,
}: VoiceAgentsListProps) {
  const [searchQuery, setSearchQuery] = useState("");

  const filteredAgents = agents.filter((agent) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      agent.userName.toLowerCase().includes(query) ||
      agent.agentId.toLowerCase().includes(query)
    );
  });

  // Loading skeleton
  if (!agents) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="p-4 border-b border-gray-200">
          <div className="h-10 bg-gray-200 rounded-lg animate-pulse" />
        </div>
        <div className="divide-y divide-gray-200">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="p-4 flex items-center gap-4">
              <div className="w-10 h-10 bg-gray-200 rounded-full animate-pulse" />
              <div className="flex-1 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/4 animate-pulse" />
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Empty state
  if (agents.length === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
        <User className="w-12 h-12 text-gray-300 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          No Voice Agents
        </h3>
        <p className="text-gray-600">
          No voice agents have been configured yet.
        </p>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      {/* Search Header */}
      <div className="p-4 border-b border-gray-200">
        <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 agents..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(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>
      </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-4">Agent / User</div>
        <div className="col-span-2 text-center">Total Calls</div>
        <div className="col-span-2 text-center">Avg Duration</div>
        <div className="col-span-3">Last Call</div>
        <div className="col-span-1"></div>
      </div>

      {/* Agents List */}
      <div className="divide-y divide-gray-200">
        {filteredAgents.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            No agents match your search
          </div>
        ) : (
          filteredAgents.map((agent) => (
            <button
              key={agent.agentId}
              onClick={() => onAgentSelect(agent.agentId)}
              className={`w-full text-left px-4 py-4 hover:bg-gray-50 transition-colors ${
                selectedAgentId === agent.agentId
                  ? "bg-blue-50 hover:bg-blue-50"
                  : ""
              }`}
            >
              {/* Mobile Layout */}
              <div className="md:hidden flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                    <User className="w-5 h-5 text-blue-600" />
                  </div>
                  <div>
                    <p className="font-medium text-gray-900">
                      {agent.userName}
                    </p>
                    <div className="flex items-center gap-3 text-sm text-gray-500 mt-0.5">
                      <span className="flex items-center gap-1">
                        <Phone className="w-3 h-3" />
                        {agent.stats.totalCalls}
                      </span>
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {formatDuration(agent.stats.avgDuration)}
                      </span>
                    </div>
                  </div>
                </div>
                <ChevronRight className="w-5 h-5 text-gray-400" />
              </div>

              {/* Desktop Layout */}
              <div className="hidden md:grid grid-cols-12 gap-4 items-center">
                <div className="col-span-4 flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                    <User className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="min-w-0">
                    <p className="font-medium text-gray-900 truncate">
                      {agent.userName}
                    </p>
                    <p className="text-xs text-gray-500 truncate">
                      ID: {agent.agentId.slice(-8)}
                    </p>
                  </div>
                </div>
                <div className="col-span-2 text-center">
                  <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gray-100 text-gray-700 text-sm font-medium">
                    <Phone className="w-3.5 h-3.5" />
                    {agent.stats.totalCalls}
                  </span>
                </div>
                <div className="col-span-2 text-center">
                  <span className="text-sm text-gray-700">
                    {formatDuration(agent.stats.avgDuration)}
                  </span>
                </div>
                <div className="col-span-3">
                  <span className="text-sm text-gray-600">
                    {formatDate(agent.stats.lastCallAt)}
                  </span>
                </div>
                <div className="col-span-1 text-right">
                  <ChevronRight className="w-5 h-5 text-gray-400 inline-block" />
                </div>
              </div>
            </button>
          ))
        )}
      </div>

      {/* Footer with count */}
      <div className="px-4 py-3 bg-gray-50 border-t border-gray-200">
        <p className="text-sm text-gray-600">
          {filteredAgents.length} of {agents.length} agent
          {agents.length !== 1 ? "s" : ""}
        </p>
      </div>
    </div>
  );
}
