"use client";

import { useState, useEffect, useCallback } from "react";
import { RefreshCw, Bot, MessageSquare, AlertCircle } from "lucide-react";
import logger from "@/lib/logger";
import VoiceAgentsStatsCards from "./VoiceAgentsStatsCards";
import VoiceAgentsList from "./VoiceAgentsList";
import VoiceConversationsList from "./VoiceConversationsList";
import VoiceTranscriptModal from "./VoiceTranscriptModal";
import NextActionsPanel from "./NextActionsPanel";
import CreateActionModal from "./CreateActionModal";
import type {
  VoiceAgentSummary,
  VoiceAgentDashboardStats,
} from "@/lib/types/voice-agent-staff.types";

interface StaffMember {
  id: string;
  name: string;
}

type TabType = "agents" | "conversations" | "actions";

export default function VoiceAgentsDashboard() {
  // Data state
  const [stats, setStats] = useState<VoiceAgentDashboardStats>({
    totalAgents: 0,
    conversationsToday: 0,
    avgDuration: 0,
    pendingActions: 0,
  });
  const [agents, setAgents] = useState<VoiceAgentSummary[]>([]);
  const [staffMembers, setStaffMembers] = useState<StaffMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // UI state
  const [activeTab, setActiveTab] = useState<TabType>("agents");
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const [selectedConversationId, setSelectedConversationId] = useState<
    string | null
  >(null);
  const [createActionConversationId, setCreateActionConversationId] = useState<
    string | null
  >(null);
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Fetch dashboard data
  const fetchDashboardData = useCallback(async () => {
    try {
      setError(null);
      const response = await fetch("/api/staff/voice-agents");

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

      const data = await response.json();
      setStats(data.stats);
      setAgents(data.agents);
      setStaffMembers(data.staffMembers);
      setLastRefresh(new Date());
    } catch (err) {
      logger.error("Failed to fetch voice agents dashboard data", {
        error: err,
      });
      setError("Failed to load dashboard data. Please try again.");
    } finally {
      setLoading(false);
      setIsRefreshing(false);
    }
  }, []);

  // Initial load
  useEffect(() => {
    fetchDashboardData();
  }, [fetchDashboardData]);

  // Auto-refresh every 60 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      fetchDashboardData();
    }, 60000);

    return () => clearInterval(interval);
  }, [fetchDashboardData]);

  // Manual refresh
  const handleRefresh = () => {
    setIsRefreshing(true);
    fetchDashboardData();
  };

  // Handle agent selection
  const handleAgentSelect = (agentId: string) => {
    setSelectedAgentId(agentId);
    setActiveTab("conversations");
  };

  // Handle conversation selection (open transcript modal)
  const handleConversationSelect = (conversationId: string) => {
    setSelectedConversationId(conversationId);
  };

  // Handle opening create action modal from transcript modal
  const handleOpenCreateAction = (conversationId: string) => {
    setCreateActionConversationId(conversationId);
  };

  // Handle action created
  const handleActionCreated = () => {
    fetchDashboardData(); // Refresh stats
  };

  // Handle action updated
  const handleActionUpdated = () => {
    fetchDashboardData(); // Refresh stats
  };

  // Tab configuration
  const tabs = [
    {
      id: "agents" as const,
      label: "Agents",
      icon: Bot,
      count: stats.totalAgents,
    },
    {
      id: "conversations" as const,
      label: "Conversations",
      icon: MessageSquare,
      count: stats.conversationsToday,
    },
    {
      id: "actions" as const,
      label: "Actions",
      icon: AlertCircle,
      count: stats.pendingActions,
    },
  ];

  // Loading state
  if (loading) {
    return (
      <div className="space-y-6">
        {/* Stats skeleton */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <div
              key={i}
              className="bg-white rounded-xl border border-gray-200 p-4 animate-pulse"
            >
              <div className="h-4 bg-gray-200 rounded w-20 mb-2" />
              <div className="h-8 bg-gray-200 rounded w-16" />
            </div>
          ))}
        </div>
        {/* Content skeleton */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="space-y-4">
            {[...Array(5)].map((_, i) => (
              <div key={i} className="h-12 bg-gray-100 rounded 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 Dashboard
        </h3>
        <p className="text-red-600 mb-4">{error}</p>
        <button
          onClick={handleRefresh}
          className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
        >
          Try Again
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <VoiceAgentsStatsCards stats={stats} />

      {/* Tabs and Refresh */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        {/* Tab Navigation */}
        <div className="flex border-b border-gray-200 sm:border-none">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 sm:rounded-lg sm:border-none transition-colors ${
                  activeTab === tab.id
                    ? "border-blue-600 text-blue-600 sm:bg-blue-50"
                    : "border-transparent text-gray-500 hover:text-gray-700 sm:hover:bg-gray-100"
                }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
                {tab.count > 0 && (
                  <span
                    className={`ml-1 px-2 py-0.5 text-xs rounded-full ${
                      activeTab === tab.id
                        ? "bg-blue-100 text-blue-700"
                        : "bg-gray-100 text-gray-600"
                    }`}
                  >
                    {tab.count}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        {/* Refresh Button and Last Updated */}
        <div className="flex items-center gap-3">
          <span className="text-xs text-gray-500">
            Updated {lastRefresh.toLocaleTimeString()}
          </span>
          <button
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition disabled:opacity-50"
          >
            <RefreshCw
              className={`w-4 h-4 ${isRefreshing ? "animate-spin" : ""}`}
            />
            Refresh
          </button>
        </div>
      </div>

      {/* Tab Content */}
      <div>
        {activeTab === "agents" && (
          <VoiceAgentsList
            agents={agents}
            onAgentSelect={handleAgentSelect}
            selectedAgentId={selectedAgentId ?? undefined}
          />
        )}

        {activeTab === "conversations" && (
          <div className="space-y-4">
            {selectedAgentId && (
              <div className="flex items-center gap-2 text-sm text-gray-600 bg-blue-50 px-4 py-2 rounded-lg">
                <span>Filtering by agent:</span>
                <span className="font-medium">
                  {agents.find((a) => a.agentId === selectedAgentId)
                    ?.userName || "Unknown"}
                </span>
                <button
                  onClick={() => setSelectedAgentId(null)}
                  className="ml-auto text-blue-600 hover:text-blue-700 font-medium"
                >
                  Clear filter
                </button>
              </div>
            )}
            <VoiceConversationsList
              agentId={selectedAgentId ?? undefined}
              onConversationSelect={handleConversationSelect}
            />
          </div>
        )}

        {activeTab === "actions" && (
          <NextActionsPanel
            staffMembers={staffMembers}
            onActionUpdated={handleActionUpdated}
          />
        )}
      </div>

      {/* Transcript Modal */}
      <VoiceTranscriptModal
        conversationId={selectedConversationId}
        isOpen={selectedConversationId !== null}
        onClose={() => setSelectedConversationId(null)}
        onOpenCreateAction={handleOpenCreateAction}
      />

      {/* Create Action Modal */}
      {createActionConversationId && (
        <CreateActionModal
          conversationId={createActionConversationId}
          staffMembers={staffMembers}
          isOpen={createActionConversationId !== null}
          onClose={() => setCreateActionConversationId(null)}
          onCreated={handleActionCreated}
        />
      )}
    </div>
  );
}
