/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/shared/common/ui/use-toast";
import { useTranslation } from "react-i18next";

// Import your existing components
import { Button } from "@/shared/common/ui/button";
import { Badge } from "@/shared/common/ui/badge";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Progress } from "@/shared/common/ui/progress";
import { cn } from "@/shared/lib/utils";
import {
  AlertCircleIcon,
  ArrowLeftIcon,
  ChartBarIcon,
  ClockIcon,
  HourglassIcon,
  Loader2,
  PlayCircleIcon,
  Settings2Icon,
  TicketIcon,
  UserIcon,
  AlertTriangleIcon,
  PhoneIcon,
  CalendarIcon,
  BuildingIcon,
  Activity,
  Zap,
  Users,
  CheckCircle,
  RefreshCw,
  TrendingUp,
  BarChart3,
  Phone,
  Clock,
} from "lucide-react";
import { getApiErrorMessage } from "@/record-management/services/api/approvalService";
import {
  useCallExecution,
  useMyActiveExecution,
} from "@/queue-management/hooks/useExecution";

// Types
enum TransferTypes {
  REASSIGN = "reassign",
  TRANSFER = "transfer",
}

enum TicketStatus {
  WAITING = "waiting",
  CALLED = "called",
  SERVING = "serving",
  COMPLETED = "completed",
  TRANSFERRED = "transferred",
  SKIPPED = "skipped",
}

interface Ticket {
  id: string;
  ticketNumber: string;

  serviceId: string;
  service: {
    name: string;
    category: {
      name: string;
    };
  };
  counterId: string;
  counter: {
    windowNumber: string;
  };
  status: TicketStatus;
  priority: "low" | "normal" | "high" | "urgent";
  calledAt?: string;
  servedAt?: string;
  completedAt?: string;
  transferredFrom?: any;
  transferredFromId?: string | null;
  transferType?: TransferTypes | null;
  handlerId?: string;
  handler?: {
    firstName: string;
    lastName: string;
    windowNumber: string;
  };
  estimatedWaitTime?: number;
  customerNotes?: string;
  customerName?: string;
  customerPhone?: string;
  queueGroup?: {
    customerName?: {
      en: string;
      am: string;
    };
    customerPhone?: string;
  };
}

const ActiveCallManagement = () => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { t } = useTranslation();

  // State
  const [activeTicket, setActiveTicket] = useState<Ticket | null>(null);
  const [serviceTime, setServiceTime] = useState(0);
  const [isTimeExceeded, setIsTimeExceeded] = useState(false);
  const [waitTime, setWaitTime] = useState(0);

  const { mutate: callExecution, isPending: isCalling } = useCallExecution();

  // Fetch active execution to show notifications
  const { data: myActiveExecutionData, refetch: refetchActiveExecution } =
    useMyActiveExecution();

  // Auto-refresh active execution data every 30 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      refetchActiveExecution();
    }, 30000); // 30 seconds

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

  // Update activeTicket when myActiveExecutionData changes
  useEffect(() => {
    if (myActiveExecutionData) {
      // Extract customer information
      const customerName =
        myActiveExecutionData.queue?.queueGroup?.customerName?.en ||
        myActiveExecutionData.queue?.queueGroup?.customerName?.am ||
        t("activeCallManagement.customer");
      const customerPhone =
        myActiveExecutionData.queue?.queueGroup?.customerPhone ||
        t("common.na", "N/A");

      // Map execution data to Ticket format
      const mappedTicket: Ticket = {
        id: myActiveExecutionData.id,
        ticketNumber: myActiveExecutionData.queue?.positionInQueue
          ? `${myActiveExecutionData.service?.prefix || "T"}-${
              myActiveExecutionData.queue.positionInQueue
            }`
          : myActiveExecutionData.queueNumber || t("common.na", "N/A"),

        serviceId: myActiveExecutionData.serviceId || "",
        service: {
          name:
            myActiveExecutionData.service?.name?.en ||
            t("activeCallManagement.service"),
          category: {
            name:
              myActiveExecutionData.service?.name?.en ||
              t("activeCallManagement.category"),
          },
        },
        counterId: myActiveExecutionData.employeePositionId || "",
        counter: {
          windowNumber: myActiveExecutionData.caseWorkerName?.en || "1",
        },
        status:
          myActiveExecutionData.status === "STARTED"
            ? TicketStatus.SERVING
            : myActiveExecutionData.status === "STOPPED"
            ? TicketStatus.CALLED
            : TicketStatus.COMPLETED,
        priority: "normal" as const,
        calledAt: myActiveExecutionData.calledAt,
        servedAt: myActiveExecutionData.startedAt,
        completedAt: myActiveExecutionData.endedAt,
        transferredFrom: undefined,
        transferredFromId: myActiveExecutionData.parentExecutionId,
        transferType: null,
        handlerId: myActiveExecutionData.caseWorkerId,
        handler: myActiveExecutionData.caseWorkerName
          ? {
              firstName:
                myActiveExecutionData.caseWorkerName.en.split(" ")[0] || "",
              lastName:
                myActiveExecutionData.caseWorkerName.en.split(" ")[1] || "",
              windowNumber: "1",
            }
          : undefined,
        estimatedWaitTime: myActiveExecutionData.service?.estimatedTime,
        customerNotes: myActiveExecutionData.queue?.queueGroup?.customerPhone
          ? `Customer: ${myActiveExecutionData.queue.queueGroup.customerName.en} (${myActiveExecutionData.queue.queueGroup.customerPhone})`
          : undefined,
        customerName: customerName,
        customerPhone: customerPhone,
        queueGroup: myActiveExecutionData.queue?.queueGroup,
      };
      setActiveTicket(mappedTicket);
    } else {
      // Clear active ticket if no execution data
      setActiveTicket(null);
    }
  }, [myActiveExecutionData, t]);

  useEffect(() => {
    let interval: number;

    if (activeTicket?.status === TicketStatus.SERVING) {
      interval = window.setInterval(() => {
        setServiceTime((prev) => {
          const newTime = prev + 1;
          // Check if time exceeded estimated time (convert minutes to seconds)
          const estimatedSeconds = (activeTicket.estimatedWaitTime || 0) * 60;
          setIsTimeExceeded(newTime > estimatedSeconds && estimatedSeconds > 0);
          return newTime;
        });
      }, 1000);
    }

    return () => clearInterval(interval);
  }, [activeTicket?.status, activeTicket?.estimatedWaitTime]);

  useEffect(() => {
    let interval: number;

    if (activeTicket?.status === TicketStatus.CALLED) {
      interval = window.setInterval(() => {
        setWaitTime((prev) => prev + 1);
      }, 1000);
    }

    return () => clearInterval(interval);
  }, [activeTicket?.status]);

  // Handlers
  const handleCall = useCallback(() => {
    callExecution(undefined, {
      onSuccess: (data) => {
        setActiveTicket(data);
        setWaitTime(0);
        toast({
          title: t("activeCallManagement.ticketCalled"),
          description: `${t("activeCallManagement.ticket")} ${
            data.ticketNumber
          } ${t("activeCallManagement.ticketCalledMessage")}`,
          variant: "default",
        });
      },
      onError: (error) => {
        toast({
          title: t("activeCallManagement.callFailed"),
          description: getApiErrorMessage(
            error,
            t("activeCallManagement.callFailedMessage")
          ),
          variant: "destructive",
        });
      },
    });
  }, [callExecution, toast, t]);

  // Helper functions
  const formatTime = useCallback((seconds: number) => {
    const h = Math.floor(seconds / 3600)
      .toString()
      .padStart(2, "0");
    const m = Math.floor((seconds % 3600) / 60)
      .toString()
      .padStart(2, "0");
    const s = (seconds % 60).toString().padStart(2, "0");
    return `${h}:${m}:${s}`;
  }, []);

  const getPriorityColor = useCallback((priority: string) => {
    switch (priority) {
      case "urgent":
        return "bg-red-100 text-red-800 border-red-200";
      case "high":
        return "bg-orange-100 text-orange-800 border-orange-200";
      case "normal":
        return "bg-blue-100 text-blue-800 border-blue-200";
      default:
        return "bg-gray-100 text-gray-800 border-gray-200";
    }
  }, []);

  // Format date for display
  const formatDate = useCallback((dateString?: string) => {
    if (!dateString) return t("common.na", "N/A");
    try {
      const date = new Date(dateString);
      return new Intl.DateTimeFormat("en-US", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      }).format(date);
    } catch {
      return dateString;
    }
  }, []);

  // Memoized components
  const TicketDisplay = useMemo(() => {
    if (!activeTicket) {
      return (
        <Card className="h-full flex items-center justify-center border-dashed border-2 border-gray-200 bg-gradient-to-br from-gray-50 to-white rounded-2xl">
          <CardContent className="py-16 text-center">
            <div className="relative inline-block mb-6">
              <div className="h-32 w-32 rounded-full bg-gradient-to-r from-blue-100 to-blue-50 flex items-center justify-center animate-pulse">
                <TicketIcon className="h-16 w-16 text-blue-300" />
              </div>
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center shadow-lg">
                  <PlayCircleIcon className="h-6 w-6 text-white" />
                </div>
              </div>
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-3">
              {t("activeCallManagement.readyToServe")}
            </h3>
            <p className="text-gray-600 max-w-md mx-auto mb-8 text-lg">
              {t("activeCallManagement.noActiveCustomer")}
            </p>
            <div className="flex items-center justify-center gap-4 text-sm text-gray-500">
              <div className="flex items-center gap-2">
                <Users className="w-4 h-4" />
                <span>
                  {t(
                    "activeCallManagement.waitingCustomers",
                    "Waiting customers"
                  )}
                </span>
              </div>
              <div className="w-1 h-1 bg-gray-300 rounded-full"></div>
              <div className="flex items-center gap-2">
                <Clock className="w-4 h-4" />
                <span>
                  {t(
                    "activeCallManagement.realTimeUpdates",
                    "Real-time updates"
                  )}
                </span>
              </div>
            </div>
          </CardContent>
        </Card>
      );
    }

    return (
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Customer Information Card */}
        <Card className="bg-white/90 backdrop-blur-sm border-0 shadow-lg rounded-2xl overflow-hidden">
          <div
            className={cn(
              "p-6 text-white",
              activeTicket.status === TicketStatus.CALLED
                ? "bg-gradient-to-r from-yellow-500 to-orange-500"
                : "bg-gradient-to-r from-purple-500 to-indigo-500"
            )}
          >
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                  <UserIcon className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="font-bold text-lg">
                    {activeTicket.status === TicketStatus.CALLED
                      ? t("activeCallManagement.customerCalled")
                      : t("activeCallManagement.currentlyServing")}
                  </h3>
                  <p className="text-white/90 text-sm">
                    {activeTicket.status === TicketStatus.CALLED
                      ? t("activeCallManagement.waitingAtCounter")
                      : t("activeCallManagement.assistingCustomer")}
                  </p>
                </div>
              </div>
              <Badge className="bg-white/20 backdrop-blur-sm text-white border-0 px-3 py-1">
                <Phone className="h-3 w-3 mr-1" />
                {activeTicket.status === TicketStatus.CALLED
                  ? t("activeCallManagement.called")
                  : t("activeCallManagement.serving")}
              </Badge>
            </div>
          </div>

          <CardContent className="p-6">
            <div className="space-y-6">
              {/* Customer Name and Ticket */}
              <div className="text-center p-6 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl">
                <div className="text-sm text-blue-600 font-medium mb-2">
                  {t("activeCallManagement.customer")}
                </div>
                <h2 className="text-3xl font-bold text-blue-900 mb-2">
                  {activeTicket.customerName ||
                    t("activeCallManagement.customer")}
                </h2>
                <div className="inline-flex items-center gap-2 bg-white px-4 py-2 rounded-full border border-blue-200">
                  <TicketIcon className="h-4 w-4 text-blue-600" />
                  <span className="text-sm font-medium text-blue-800">
                    {t("activeCallManagement.ticket")} #
                    {activeTicket.ticketNumber}
                  </span>
                </div>
              </div>

              {/* Customer Details Grid */}
              <div className="grid grid-cols-1 gap-4">
                <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                      <PhoneIcon className="h-5 w-5 text-primary-600" />
                    </div>
                    <div>
                      <div className="text-sm text-primary-600 font-medium">
                        {t("activeCallManagement.phoneNumber")}
                      </div>
                      <div className="font-semibold text-green-900">
                        {activeTicket.customerPhone || t("common.na", "N/A")}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex items-center justify-between p-4 bg-purple-50 rounded-lg border border-purple-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                      <CalendarIcon className="h-5 w-5 text-purple-600" />
                    </div>
                    <div>
                      <div className="text-sm text-purple-600 font-medium">
                        {t("activeCallManagement.calledAt", "Called At")}
                      </div>
                      <div className="font-semibold text-purple-900">
                        {formatDate(activeTicket.calledAt)}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Priority Badge */}
              {activeTicket.priority && activeTicket.priority !== "normal" && (
                <div className="flex items-center justify-center">
                  <Badge
                    className={cn(
                      "px-4 py-2 text-sm font-semibold",
                      getPriorityColor(activeTicket.priority)
                    )}
                  >
                    <AlertTriangleIcon className="h-4 w-4 mr-2" />
                    {activeTicket.priority.toUpperCase()}{" "}
                    {t("activeCallManagement.priority", "PRIORITY")}
                  </Badge>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Service Information Card */}
        <Card className="bg-white/90 backdrop-blur-sm border-0 shadow-lg rounded-2xl overflow-hidden">
          <div className="p-6 bg-gradient-to-r from-blue-600 to-cyan-500 text-white">
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                  <Settings2Icon className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="font-bold text-lg">
                    {t("activeCallManagement.serviceInformation")}
                  </h3>
                  <p className="text-white/90 text-sm">
                    {t("activeCallManagement.currentServiceDetails")}
                  </p>
                </div>
              </div>
              <Badge className="bg-white/20 backdrop-blur-sm text-white border-0 px-3 py-1">
                <Settings2Icon className="h-3 w-3 mr-1" />
                {t("activeCallManagement.service")}
              </Badge>
            </div>
          </div>

          <CardContent className="p-6">
            <div className="space-y-6">
              {/* Service Name Display */}
              <div className="text-center p-6 bg-gradient-to-r from-cyan-50 to-blue-50 rounded-xl">
                <div className="text-sm text-cyan-600 font-medium mb-2">
                  {t(
                    "activeCallManagement.currentlyServingLabel",
                    "Currently Serving"
                  )}
                </div>
                <h2 className="text-2xl font-bold text-cyan-900 mb-4">
                  {typeof activeTicket.service?.name === "object"
                    ? (activeTicket.service?.name as any)?.en ||
                      (activeTicket.service?.name as any)?.am ||
                      t("activeCallManagement.service")
                    : activeTicket.service?.name}
                </h2>
                <div className="inline-flex items-center gap-2 bg-white px-4 py-2 rounded-full border border-cyan-200">
                  <BuildingIcon className="h-4 w-4 text-cyan-600" />
                  <span className="text-sm font-medium text-cyan-800">
                    {t("activeCallManagement.window")}{" "}
                    {activeTicket.counter?.windowNumber ||
                      t("common.na", "N/A")}
                  </span>
                </div>
              </div>

              {/* Service Details */}
              <div className="grid grid-cols-1 gap-4">
                <div className="flex items-center justify-between p-4 bg-orange-50 rounded-lg border border-orange-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
                      <ClockIcon className="h-5 w-5 text-orange-600" />
                    </div>
                    <div>
                      <div className="text-sm text-orange-600 font-medium">
                        {t("activeCallManagement.estimatedTime", "Est. Time")}
                      </div>
                      <div className="font-semibold text-orange-900">
                        {activeTicket.estimatedWaitTime
                          ? `${activeTicket.estimatedWaitTime} ${t(
                              "activeCallManagement.minutes",
                              "minutes"
                            )}`
                          : t(
                              "activeCallManagement.notSpecified",
                              "Not specified"
                            )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex items-center justify-between p-4 bg-indigo-50 rounded-lg border border-indigo-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
                      <ChartBarIcon className="h-5 w-5 text-indigo-600" />
                    </div>
                    <div>
                      <div className="text-sm text-indigo-600 font-medium">
                        {t("activeCallManagement.status")}
                      </div>
                      <div className="font-semibold text-indigo-900 capitalize">
                        {activeTicket.status === TicketStatus.SERVING
                          ? t("activeCallManagement.inProgress")
                          : activeTicket.status === TicketStatus.CALLED
                          ? t("activeCallManagement.waiting")
                          : activeTicket.status}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Service Start Time */}
              {activeTicket.servedAt && (
                <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border border-green-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                      <CheckCircle className="h-5 w-5 text-primary-600" />
                    </div>
                    <div>
                      <div className="text-sm font-medium text-green-800">
                        {t("activeCallManagement.serviceStarted")}
                      </div>
                      <div className="text-sm text-primary-700">
                        {formatDate(activeTicket.servedAt)}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Customer Notes */}
              {activeTicket.customerNotes && (
                <div className="p-4 bg-gradient-to-r from-amber-50 to-yellow-50 rounded-lg border border-amber-200">
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center mt-0.5">
                      <AlertCircleIcon className="h-5 w-5 text-amber-600" />
                    </div>
                    <div>
                      <div className="text-sm font-medium text-amber-800 mb-1">
                        {t("activeCallManagement.customerNotes")}
                      </div>
                      <div className="text-sm text-amber-700">
                        {activeTicket.customerNotes}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }, [activeTicket, handleCall, isCalling, getPriorityColor, formatDate, t]);

  const ServingTime = () => {
    if (!activeTicket) return null;

    const time =
      activeTicket.status === TicketStatus.SERVING ? serviceTime : waitTime;
    const isServing = activeTicket.status === TicketStatus.SERVING;
    const maxTime = (activeTicket.estimatedWaitTime || 5) * 60;
    const progressValue = Math.min((time / maxTime) * 100, 100);
    const isOverdue = isTimeExceeded;

    return (
      <Card className="bg-white/90 backdrop-blur-sm border-0 shadow-lg rounded-2xl overflow-hidden">
        <div
          className={cn(
            "p-6",
            isServing
              ? isOverdue
                ? "bg-gradient-to-r from-red-500 to-rose-500"
                : "bg-gradient-to-r from-green-500 to-emerald-500"
              : isOverdue
              ? "bg-gradient-to-r from-red-500 to-rose-500"
              : "bg-gradient-to-r from-yellow-500 to-amber-500"
          )}
        >
          <div className="flex items-center justify-between text-white">
            <div className="flex items-center gap-4">
              <div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center">
                <ClockIcon className="w-8 h-8" />
              </div>
              <div>
                <h3 className="text-2xl font-bold mb-1">
                  {isServing
                    ? t("activeCallManagement.serviceTime")
                    : t("activeCallManagement.customerWaitTime")}
                </h3>
                <p className="text-white/90">
                  {isServing
                    ? isOverdue
                      ? `⚠️ ${t(
                          "activeCallManagement.exceedingEstimatedTime"
                        )} ${activeTicket.customerName}`
                      : `${t("activeCallManagement.assisting")} ${
                          activeTicket.customerName
                        }`
                    : `${activeTicket.customerName} ${t(
                        "activeCallManagement.waitingAtCounterLabel"
                      )}`}
                </p>
              </div>
            </div>
            <div className="text-right">
              <div className="text-5xl font-bold font-mono mb-2">
                {formatTime(time)}
              </div>
              <div className="flex items-center gap-2">
                <Badge
                  className={cn(
                    "px-3 py-1.5 text-sm font-semibold",
                    isOverdue
                      ? "bg-white/20 text-white"
                      : "bg-white/20 text-white"
                  )}
                >
                  {progressValue.toFixed(0)}%
                </Badge>
                <span className="text-sm text-white/80">
                  {Math.floor(maxTime / 60)}m {t("activeCallManagement.target")}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-gray-50 p-6">
          <div className="flex justify-between items-center mb-4">
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <ClockIcon className="w-5 h-5 text-gray-600" />
                <span className="text-sm font-medium text-gray-700">
                  {t("activeCallManagement.timeElapsed")}
                </span>
              </div>
              <div className="text-lg font-mono font-semibold text-gray-900">
                {Math.floor(time / 60)}m {time % 60}s
              </div>
            </div>
            <div className="flex items-center gap-2">
              {isOverdue && (
                <Badge variant="destructive" className="gap-1">
                  <AlertTriangleIcon className="w-3 h-3" />
                  {t("activeCallManagement.overdue", "Overdue")}
                </Badge>
              )}
              <Badge
                variant={isServing ? "success" : "warning"}
                className="gap-1"
              >
                <Activity className="w-3 h-3" />
                {isServing
                  ? t("activeCallManagement.serving")
                  : t("activeCallManagement.waiting")}
              </Badge>
            </div>
          </div>
          <Progress
            value={progressValue}
            className={cn(
              "h-3 rounded-full",
              isOverdue
                ? "bg-red-100 [&>div]:bg-gradient-to-r [&>div]:from-red-500 [&>div]:to-rose-500"
                : isServing
                ? "bg-green-100 [&>div]:bg-gradient-to-r [&>div]:from-green-500 [&>div]:to-emerald-500"
                : "bg-yellow-100 [&>div]:bg-gradient-to-r [&>div]:from-yellow-500 [&>div]:to-amber-500"
            )}
          />
          <div className="flex justify-between text-xs text-gray-500 mt-2">
            <span>0m</span>
            <span>{Math.floor(maxTime / 60)}m</span>
          </div>
        </div>
      </Card>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 p-4 md:p-6">
      <div className="max-w-7xl mx-auto">
        {/* Enhanced Header */}
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              size="sm"
              onClick={() => navigate(-1)}
              className="border-gray-300 hover:border-blue-400 hover:bg-blue-50 gap-2"
            >
              <ArrowLeftIcon className="h-4 w-4" />
              {t("activeCallManagement.back", "Back")}
            </Button>
            <div className="flex items-center gap-4">
              <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-2xl flex items-center justify-center shadow-lg">
                <Activity className="w-8 h-8 text-white" />
              </div>
              <div>
                <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 via-cyan-600 to-indigo-600 bg-clip-text text-transparent mb-2">
                  {t("activeCallManagement.title", "Active Call Management")}
                </h1>
                <p className="text-gray-600 text-lg flex items-center gap-2">
                  <Zap className="w-5 h-5 text-blue-500" />
                  {t(
                    "activeCallManagement.description",
                    "Manage active customer calls and service execution in real-time"
                  )}
                </p>
              </div>
            </div>
          </div>

          {/* Real-time Status and Controls */}
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 px-4 py-2 bg-white/80 backdrop-blur-sm rounded-xl shadow-sm border">
              <div className="w-3 h-3 rounded-full bg-green-500 animate-pulse" />
              <span className="text-sm font-medium text-gray-700">
                {t("activeCallManagement.realTimeUpdates", "Real-time Updates")}
              </span>
            </div>
            <div className="flex items-center gap-3">
              <div className="text-right">
                <p className="text-sm text-gray-500">
                  {t("activeCallManagement.serviceCounter", "Service Counter")}
                </p>
                <Badge className="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-3 py-1.5">
                  {t("activeCallManagement.window", "Window")}{" "}
                  {activeTicket?.counter?.windowNumber || t("common.na", "N/A")}
                </Badge>
              </div>
              <div className="h-8 w-px bg-gray-300" />
              <div className="text-right">
                <p className="text-sm text-gray-500">
                  {t("activeCallManagement.status", "Status")}
                </p>
                <Badge
                  className={cn(
                    "px-3 py-1.5",
                    activeTicket
                      ? "bg-gradient-to-r from-green-500 to-emerald-500 text-white"
                      : "bg-gray-100 text-gray-800"
                  )}
                >
                  {activeTicket
                    ? t("activeCallManagement.active", "Active")
                    : t("activeCallManagement.ready", "Ready")}
                </Badge>
              </div>
            </div>
          </div>
        </div>

        {/* Enhanced Main Content */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Left Sidebar - Quick Actions & Stats */}
          <div className="lg:col-span-1 space-y-6">
            {/* Quick Actions Card */}
            <Card className="bg-white/90 backdrop-blur-sm border-0 shadow-lg rounded-2xl overflow-hidden">
              <div className="p-6 bg-gradient-to-r from-blue-600 to-blue-500 text-white">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                    <Zap className="w-5 h-5" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-lg">
                      {t("activeCallManagement.quickActions")}
                    </h3>
                    <p className="text-blue-100 text-sm">
                      {t("activeCallManagement.commonOperations")}
                    </p>
                  </div>
                </div>
              </div>
              <CardContent className="p-6 space-y-4">
                {/* Call Next Customer Button */}
                <Button
                  className="w-full bg-gradient-to-r from-green-500 to-emerald-500 hover:from-primary hover:to-emerald-600 text-white shadow-lg hover:shadow-xl transition-all duration-200 h-12"
                  onClick={() => handleCall()}
                  disabled={isCalling || !!activeTicket}
                >
                  {isCalling ? (
                    <>
                      <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                      {t("activeCallManagement.calling")}
                    </>
                  ) : (
                    <>
                      <PlayCircleIcon className="h-5 w-5 mr-2" />
                      {t("activeCallManagement.callNextCustomer")}
                    </>
                  )}
                </Button>

                {/* Action Buttons Grid */}
                <div className="grid grid-cols-1 gap-3">
                  <Button
                    variant="outline"
                    className="border-gray-300 text-gray-700 hover:bg-gray-50 h-10 gap-2"
                    disabled={!activeTicket}
                  >
                    <HourglassIcon className="h-4 w-4" />
                    {t("activeCallManagement.hold")}
                  </Button>
                  <Button
                    variant="outline"
                    className="border-gray-300 text-gray-700 hover:bg-gray-50 h-10 gap-2"
                    disabled={!activeTicket}
                  >
                    <Settings2Icon className="h-4 w-4" />
                    {t("activeCallManagement.transfer")}
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => {
                      refetchActiveExecution();
                    }}
                    className="border-gray-300 text-gray-700 hover:bg-gray-50 h-10 gap-2"
                  >
                    <RefreshCw className="h-4 w-4" />
                    {t("activeCallManagement.refresh", "Refresh")}
                  </Button>
                </div>
              </CardContent>
            </Card>

            {/* Customer Stats Card */}
            {activeTicket && (
              <Card className="bg-white/90 backdrop-blur-sm border-0 shadow-lg rounded-2xl overflow-hidden">
                <div className="p-6 bg-gradient-to-r from-purple-600 to-violet-500 text-white">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                      <BarChart3 className="w-5 h-5" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg">
                        {t("activeCallManagement.customerStats")}
                      </h3>
                      <p className="text-purple-100 text-sm">
                        {t(
                          "activeCallManagement.realTimeMetrics",
                          "Real-time metrics"
                        )}
                      </p>
                    </div>
                  </div>
                </div>
                <CardContent className="p-6">
                  <div className="space-y-4">
                    <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <Settings2Icon className="h-4 w-4 text-blue-600" />
                        <span className="text-sm text-blue-700 font-medium">
                          {t("activeCallManagement.currentService")}
                        </span>
                      </div>
                      <span className="font-medium text-blue-900 text-sm">
                        {typeof activeTicket.service?.name === "object"
                          ? (activeTicket.service?.name as any)?.en ||
                            (activeTicket.service?.name as any)?.am ||
                            t("common.na", "N/A")
                          : activeTicket.service?.name}
                      </span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-yellow-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <Clock className="h-4 w-4 text-yellow-600" />
                        <span className="text-sm text-yellow-700 font-medium">
                          {t("activeCallManagement.waitTime")}
                        </span>
                      </div>
                      <span className="font-medium text-yellow-900 font-mono">
                        {formatTime(waitTime)}
                      </span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <Activity className="h-4 w-4 text-primary-600" />
                        <span className="text-sm text-primary-700 font-medium">
                          {t("activeCallManagement.serviceTime")}
                        </span>
                      </div>
                      <span className="font-medium text-green-900 font-mono">
                        {formatTime(serviceTime)}
                      </span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <TrendingUp className="h-4 w-4 text-purple-600" />
                        <span className="text-sm text-purple-700 font-medium">
                          {t("activeCallManagement.priority")}
                        </span>
                      </div>
                      <Badge
                        className={cn(
                          "px-2 py-0.5",
                          getPriorityColor(activeTicket.priority)
                        )}
                      >
                        {activeTicket.priority}
                      </Badge>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>

          {/* Main Content Area */}
          <div className="lg:col-span-3 space-y-6">
            {/* Timer Card */}
            {activeTicket && <ServingTime />}

            {/* Customer and Service Display */}
            {TicketDisplay}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ActiveCallManagement;
