'use client';

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import {
  Search,
  Filter,
  Ticket,
  Clock,
  User,
  MapPin,
  CheckCircle2,
  Circle,
  Loader2,
  ChevronRight,
  ChevronDown,
  AlertCircle,
  Wrench,
  Monitor,
  Wifi,
  Package,
  MessageSquare,
  X,
  RefreshCw,
  FileText,
  Calendar,
  ArrowLeft,
  Sparkles,
  Paperclip,
  Hash,
  Shield,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Progress } from '@/components/ui/progress';

interface ComplaintUpdate {
  id: string;
  updateType: string;
  title: string;
  description: string;
  updatedBy: string;
  createdAt: string;
}

interface Complaint {
  id: string;
  ticketNumber: string;
  clientName: string;
  clientPhone: string;
  clientEmail?: string;
  complaintType: string;
  priority: string;
  status: string;
  description: string;
  area: { id: string; name: string; code: string };
  assignedHOD?: { id: string; name: string; email: string } | null;
  assignedEngineer?: { id: string; name: string; email: string } | null;
  assignedVendor?: { id: string; name: string; email: string } | null;
  resolution?: string | null;
  createdAt: string;
  updatedAt: string;
  completedAt?: string | null;
  updates?: ComplaintUpdate[];
}

const STATUS_FLOW = ['pending', 'assigned', 'in_progress', 'diagnosed', 'resolved'];

const STATUS_COLORS: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700 border-amber-200',
  assigned: 'bg-blue-100 text-blue-700 border-blue-200',
  in_progress: 'bg-purple-100 text-purple-700 border-purple-200',
  diagnosed: 'bg-cyan-100 text-cyan-700 border-cyan-200',
  resolved: 'bg-emerald-100 text-emerald-700 border-emerald-200',
  closed: 'bg-gray-100 text-gray-600 border-gray-200',
};

const PRIORITY_COLORS: Record<string, string> = {
  low: 'bg-slate-100 text-slate-600',
  medium: 'bg-amber-100 text-amber-700',
  high: 'bg-orange-100 text-orange-700',
  critical: 'bg-red-100 text-red-700',
};

const TYPE_ICONS: Record<string, React.ReactNode> = {
  hardware: <Monitor className="w-4 h-4" />,
  software: <Package className="w-4 h-4" />,
  network: <Wifi className="w-4 h-4" />,
  other: <AlertCircle className="w-4 h-4" />,
};

const STATUS_LABEL_MAP: Record<string, string> = {
  pending: 'pending',
  assigned: 'assigned',
  in_progress: 'inProgress',
  diagnosed: 'diagnosed',
  resolved: 'resolved',
  closed: 'closed',
  reopened: 'reopened',
  overdue: 'overdue',
  escalated: 'escalated',
  draft: 'draft',
};

function getStatusLabel(status: string, t: { status: Record<string, string> }): string {
  const key = STATUS_LABEL_MAP[status] || status;
  return t.status[key] || status;
}

function formatDate(dateStr: string, language: string): string {
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString(language === 'bn' ? 'bn-BD' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return dateStr;
  }
}

function formatDateShort(dateStr: string, language: string): string {
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString(language === 'bn' ? 'bn-BD' : 'en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    });
  } catch {
    return dateStr;
  }
}

function getUpdateIcon(updateType: string) {
  switch (updateType) {
    case 'status_change':
      return <CheckCircle2 className="w-4 h-4 text-emerald-500" />;
    case 'diagnosis':
      return <Wrench className="w-4 h-4 text-cyan-500" />;
    case 'resolution':
      return <CheckCircle2 className="w-4 h-4 text-green-500" />;
    case 'note':
      return <MessageSquare className="w-4 h-4 text-blue-500" />;
    default:
      return <Circle className="w-4 h-4 text-gray-400" />;
  }
}

// ─── Ticket Detail Modal Component ─────────────────────────────────────────

function TicketDetailModal({
  complaint,
  open,
  onClose,
  language,
  t,
  onSearchTicket,
}: {
  complaint: Complaint | null;
  open: boolean;
  onClose: () => void;
  language: string;
  t: ReturnType<typeof useTranslation>['t'];
  onSearchTicket: (ticketNumber: string) => void;
}) {
  const [trackInput, setTrackInput] = useState('');

  if (!complaint) return null;

  const statusStep = STATUS_FLOW.indexOf(complaint.status);
  const currentStep = statusStep >= 0 ? statusStep : 0;
  const progressPercent = (currentStep / (STATUS_FLOW.length - 1)) * 100;
  const active = ['assigned', 'in_progress'].includes(complaint.status);

  const handleTrackAnother = () => {
    if (trackInput.trim()) {
      onSearchTicket(trackInput.trim());
      setTrackInput('');
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-2xl w-[95vw] max-h-[90vh] p-0 gap-0 overflow-hidden">
        <DialogTitle className="sr-only">
          Ticket {complaint.ticketNumber} Details
        </DialogTitle>
        <div className="flex flex-col h-full max-h-[90vh]">
          {/* Modal Header with search */}
          <div className="flex-shrink-0 bg-gradient-to-r from-emerald-700 to-emerald-800 text-white p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Ticket className="w-5 h-5" />
                <span className="font-bold text-lg">{complaint.ticketNumber}</span>
                <Badge className="bg-white/20 text-white border-white/30 text-xs">
                  {getStatusLabel(complaint.status, t)}
                </Badge>
              </div>
              <Button
                variant="ghost"
                size="icon"
                onClick={onClose}
                className="text-white hover:bg-white/20 h-8 w-8"
              >
                <X className="w-4 h-4" />
              </Button>
            </div>
            {/* Track Another Ticket */}
            <div className="flex gap-2">
              <div className="relative flex-1">
                <Hash className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-emerald-300" />
                <Input
                  placeholder="Track another ticket number..."
                  value={trackInput}
                  onChange={(e) => setTrackInput(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleTrackAnother()}
                  className="pl-8 h-8 bg-white/10 border-white/20 text-white placeholder:text-emerald-200 text-sm focus:bg-white/20"
                />
              </div>
              <Button
                onClick={handleTrackAnother}
                size="sm"
                className="h-8 bg-white/20 hover:bg-white/30 text-white border-white/20"
              >
                <Search className="w-3.5 h-3.5 mr-1" />
                Track
              </Button>
            </div>
          </div>

          {/* Scrollable Content */}
          <ScrollArea className="flex-1 min-h-0">
            <div className="p-5 space-y-5">
              {/* Status Progress Bar */}
              <div>
                <h4 className="text-sm font-semibold text-emerald-800 mb-3">Status Progress</h4>
                <div className="mb-3">
                  <Progress value={progressPercent} className="h-2 bg-emerald-100" />
                </div>
                <div className="flex items-center justify-between">
                  {STATUS_FLOW.map((step, idx) => {
                    const isCompleted = idx <= currentStep;
                    const isCurrent = idx === currentStep;
                    return (
                      <div key={step} className="flex flex-col items-center flex-1 min-w-0">
                        <div
                          className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold transition-all ${
                            isCompleted
                              ? isCurrent && active
                                ? 'bg-emerald-500 text-white animate-pulse-green'
                                : 'bg-emerald-500 text-white'
                              : 'bg-gray-100 text-gray-400'
                          }`}
                        >
                          {isCompleted ? '✓' : idx + 1}
                        </div>
                        <span
                          className={`text-[10px] mt-1 text-center whitespace-nowrap ${
                            isCompleted ? 'text-emerald-700 font-semibold' : 'text-gray-400'
                          }`}
                        >
                          {getStatusLabel(step, t)}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>

              <Separator className="bg-emerald-100" />

              {/* Full Ticket Info */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-3">
                  <div>
                    <span className="text-xs font-medium text-emerald-600 uppercase tracking-wider">
                      {t.complaint.description}
                    </span>
                    <p className="text-sm text-gray-700 mt-1">{complaint.description}</p>
                  </div>
                  {complaint.resolution && (
                    <div>
                      <span className="text-xs font-medium text-emerald-600 uppercase tracking-wider">
                        {t.complaint.resolution}
                      </span>
                      <p className="text-sm text-gray-700 mt-1 bg-emerald-50 p-3 rounded-lg border border-emerald-100">
                        {complaint.resolution}
                      </p>
                    </div>
                  )}
                </div>
                <div className="space-y-2.5">
                  <div className="flex items-center gap-2 text-sm">
                    <Badge variant="secondary" className={`text-[11px] px-2 py-0 ${PRIORITY_COLORS[complaint.priority] || ''}`}>
                      {t.priority[complaint.priority as keyof typeof t.priority] || complaint.priority}
                    </Badge>
                    <Badge variant="outline" className={`text-[11px] px-2 py-0 ${STATUS_COLORS[complaint.status] || ''}`}>
                      {getStatusLabel(complaint.status, t)}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <User className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">{t.complaint.clientName}:</span>
                    <span className="font-medium text-emerald-800">{complaint.clientName}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <MapPin className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">{t.complaint.area}:</span>
                    <span className="font-medium">{complaint.area?.name}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <Wrench className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">{t.complaint.assignedTo}:</span>
                    <span className="font-medium text-emerald-800">
                      {complaint.assignedEngineer?.name || complaint.assignedHOD?.name || 'Unassigned'}
                    </span>
                  </div>
                  {complaint.assignedVendor && (
                    <div className="flex items-center gap-2 text-sm">
                      <Package className="w-4 h-4 text-emerald-500" />
                      <span className="text-muted-foreground">Vendor:</span>
                      <span className="font-medium text-emerald-800">{complaint.assignedVendor.name}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-2 text-sm">
                    <Calendar className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">{t.complaint.createdAt}:</span>
                    <span className="font-medium">{formatDate(complaint.createdAt, language)}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <Clock className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">{t.complaint.updatedAt}:</span>
                    <span className="font-medium">{formatDate(complaint.updatedAt, language)}</span>
                  </div>
                  {complaint.completedAt && (
                    <div className="flex items-center gap-2 text-sm">
                      <CheckCircle2 className="w-4 h-4 text-emerald-500" />
                      <span className="text-muted-foreground">{t.complaint.resolvedAt}:</span>
                      <span className="font-medium">{formatDate(complaint.completedAt, language)}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-2 text-sm">
                    <MessageSquare className="w-4 h-4 text-emerald-500" />
                    <span className="text-muted-foreground">WhatsApp:</span>
                    <Badge variant="outline" className="text-[11px] bg-green-50 text-green-700 border-green-200">
                      Notifications Active
                    </Badge>
                  </div>
                </div>
              </div>

              <Separator className="bg-emerald-100" />

              {/* Attachments */}
              <div>
                <h4 className="text-sm font-semibold text-emerald-800 mb-2 flex items-center gap-2">
                  <Paperclip className="w-4 h-4" />
                  {t.complaint.attachments}
                </h4>
                <div className="text-sm text-muted-foreground bg-gray-50 rounded-lg p-3 border border-gray-100">
                  <div className="flex items-center gap-2">
                    <FileText className="w-4 h-4 text-gray-400" />
                    No attachments available for this ticket
                  </div>
                </div>
              </div>

              <Separator className="bg-emerald-100" />

              {/* Full Timeline */}
              <div>
                <h4 className="text-sm font-semibold text-emerald-800 mb-3 flex items-center gap-2">
                  <Clock className="w-4 h-4" />
                  {t.complaint.timeline}
                </h4>
                {complaint.updates && complaint.updates.length > 0 ? (
                  <div className="space-y-0">
                    {complaint.updates
                      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                      .map((update, idx) => (
                        <div key={update.id} className="flex gap-3">
                          <div className="flex flex-col items-center">
                            <div className="w-8 h-8 rounded-full bg-white border-2 border-emerald-200 flex items-center justify-center flex-shrink-0">
                              {getUpdateIcon(update.updateType)}
                            </div>
                            {idx < (complaint.updates?.length || 0) - 1 && (
                              <div className="w-0.5 h-full bg-emerald-100 my-0.5" />
                            )}
                          </div>
                          <div className="pb-4 min-w-0 flex-1">
                            <p className="text-sm font-medium text-emerald-800">{update.title}</p>
                            <p className="text-xs text-gray-600 mt-0.5">{update.description}</p>
                            <div className="flex items-center gap-2 mt-1">
                              <p className="text-[11px] text-muted-foreground">
                                {formatDate(update.createdAt, language)}
                              </p>
                              {update.updatedBy && (
                                <span className="text-[11px] text-emerald-600">by {update.updatedBy}</span>
                              )}
                            </div>
                          </div>
                        </div>
                      ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">{t.common.noData}</p>
                )}
              </div>

              {/* Resolution Details */}
              {complaint.status === 'resolved' && complaint.resolution && (
                <>
                  <Separator className="bg-emerald-100" />
                  <div>
                    <h4 className="text-sm font-semibold text-emerald-800 mb-2 flex items-center gap-2">
                      <CheckCircle2 className="w-4 h-4" />
                      Resolution Details
                    </h4>
                    <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
                      <p className="text-sm text-emerald-900">{complaint.resolution}</p>
                      {complaint.completedAt && (
                        <p className="text-xs text-emerald-600 mt-2">
                          Resolved on {formatDate(complaint.completedAt, language)}
                        </p>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>
          </ScrollArea>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ─── Main TicketTracking Component ─────────────────────────────────────────

export default function TicketTracking() {
  const currentUser = useStore((s) => s.currentUser);
  const language = useStore((s) => s.language);
  const setView = useStore((s) => s.setView);
  const { t } = useTranslation();

  // Extract primitive values from currentUser to avoid object reference in deps
  const currentUserId = currentUser?.id;
  const currentUserPhone = currentUser?.phone;
  const currentUserNname = currentUser?.name;

  const [allComplaints, setAllComplaints] = useState<Complaint[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  // Always filter by logged-in client's tickets - no toggle needed
  const [expandedTicket, setExpandedTicket] = useState<string | null>(null);
  const [expandedDetails, setExpandedDetails] = useState<Complaint | null>(null);
  const [detailsLoading, setDetailsLoading] = useState(false);

  // Ticket number search
  const [ticketNumberSearch, setTicketNumberSearch] = useState('');
  const [searchedTicket, setSearchedTicket] = useState<Complaint | null>(null);
  const [searchedTicketLoading, setSearchedTicketLoading] = useState(false);
  const [searchedTicketError, setSearchedTicketError] = useState('');

  // Detail modal
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [detailModalComplaint, setDetailModalComplaint] = useState<Complaint | null>(null);
  const [detailModalLoading, setDetailModalLoading] = useState(false);

  // Debounce search to avoid excessive re-renders
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearchQuery(searchQuery), 400);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  const fetchComplaints = useCallback(async (isRefresh = false) => {
    if (!currentUserId) return;
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    try {
      const params = new URLSearchParams();
      if (statusFilter !== 'all') {
        params.set('status', statusFilter);
      }
      params.set('limit', '100');

      // Always filter by logged-in client's ID for strict data isolation
      params.set('userId', currentUserId);

      // Also pass phone and name for backward compatibility
      if (currentUserPhone) {
        params.set('clientPhone', currentUserPhone);
      }
      if (currentUserNname) {
        params.set('clientName', currentUserNname);
      }

      const res = await fetch(`/api/complaints?${params.toString()}`);
      if (res.ok) {
        const data = await res.json();
        let complaints = data.complaints || [];

        // Additional client-side search filtering (ticket number, description, etc.)
        if (debouncedSearchQuery.trim()) {
          const query = debouncedSearchQuery.toLowerCase();
          complaints = complaints.filter(
            (c: Complaint) =>
              c.ticketNumber.toLowerCase().includes(query) ||
              c.description.toLowerCase().includes(query) ||
              c.clientName.toLowerCase().includes(query) ||
              c.clientPhone.toLowerCase().includes(query)
          );
        }

        setAllComplaints(complaints);
      }
    } catch (err) {
      console.error('Failed to fetch complaints:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [currentUserId, currentUserPhone, currentUserNname, statusFilter, debouncedSearchQuery]);

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

  // Compute stats from allComplaints
  const stats = useMemo(() => {
    const total = allComplaints.length;
    const pending = allComplaints.filter((c) => c.status === 'pending').length;
    const inProgress = allComplaints.filter((c) => c.status === 'assigned' || c.status === 'in_progress').length;
    const resolved = allComplaints.filter((c) => c.status === 'resolved').length;
    const closed = allComplaints.filter((c) => c.status === 'closed').length;
    return { total, pending, inProgress, resolved, closed };
  }, [allComplaints]);

  // User profile summary
  const userProfile = useMemo(() => {
    const activeCount = allComplaints.filter(
      (c) => c.status !== 'resolved' && c.status !== 'closed'
    ).length;
    const lastDate = allComplaints.length > 0
      ? allComplaints.reduce((latest, c) => {
          const d = new Date(c.createdAt);
          return d > latest ? d : latest;
        }, new Date(0))
      : null;
    return { activeCount, lastDate };
  }, [allComplaints]);

  const fetchTicketDetails = async (complaintId: string) => {
    setDetailsLoading(true);
    try {
      const res = await fetch(`/api/complaints/${complaintId}`);
      if (res.ok) {
        const data = await res.json();
        setExpandedDetails(data.complaint);
      }
    } catch (err) {
      console.error('Failed to fetch ticket details:', err);
    } finally {
      setDetailsLoading(false);
    }
  };

  const openDetailModal = async (complaint: Complaint) => {
    setDetailModalComplaint(complaint);
    setDetailModalOpen(true);
    setDetailModalLoading(true);
    try {
      const res = await fetch(`/api/complaints/${complaint.id}`);
      if (res.ok) {
        const data = await res.json();
        setDetailModalComplaint(data.complaint);
      }
    } catch (err) {
      console.error('Failed to fetch full ticket details:', err);
    } finally {
      setDetailModalLoading(false);
    }
  };

  const handleSearchByTicketNumber = async (ticketNum?: string) => {
    const searchValue = ticketNum || ticketNumberSearch;
    if (!searchValue.trim()) return;
    setSearchedTicketLoading(true);
    setSearchedTicketError('');
    setSearchedTicket(null);
    try {
      const params = new URLSearchParams();
      params.set('ticketNumber', searchValue.trim());
      params.set('limit', '1');
      params.set('userId', currentUser?.id || '');
      if (currentUser?.phone) params.set('clientPhone', currentUser.phone);
      if (currentUser?.name) params.set('clientName', currentUser.name);
      const res = await fetch(`/api/complaints?${params.toString()}`);
      if (res.ok) {
        const data = await res.json();
        const complaints = data.complaints || [];
        if (complaints.length > 0) {
          const ticket = complaints[0];
          // Server-side userId filter already ensures data isolation, but double-check
          const belongsToClient =
            (currentUser?.phone && ticket.clientPhone && ticket.clientPhone.includes(currentUser.phone)) ||
            (currentUser?.name && ticket.clientName && ticket.clientName.includes(currentUser.name));

          if (!belongsToClient) {
            setSearchedTicketError('This ticket does not belong to your account.');
          } else {
            // Fetch full details
            const detailRes = await fetch(`/api/complaints/${complaints[0].id}`);
            if (detailRes.ok) {
              const detailData = await detailRes.json();
              setSearchedTicket(detailData.complaint);
            } else {
              setSearchedTicket(complaints[0]);
            }
          }
        } else {
          setSearchedTicketError('Ticket not found. Please check the ticket number and try again.');
        }
      } else {
        setSearchedTicketError('Failed to search. Please try again.');
      }
    } catch {
      setSearchedTicketError('Network error. Please try again.');
    } finally {
      setSearchedTicketLoading(false);
    }
  };

  const handleTrackFromModal = (ticketNumber: string) => {
    setTicketNumberSearch(ticketNumber);
    handleSearchByTicketNumber(ticketNumber);
    setDetailModalOpen(false);
  };

  const toggleTicket = (ticketId: string) => {
    if (expandedTicket === ticketId) {
      setExpandedTicket(null);
      setExpandedDetails(null);
    } else {
      setExpandedTicket(ticketId);
      fetchTicketDetails(ticketId);
    }
  };

  const getStatusStepIndex = (status: string): number => {
    const idx = STATUS_FLOW.indexOf(status);
    return idx >= 0 ? idx : 0;
  };

  const isActive = (status: string): boolean => {
    return ['assigned', 'in_progress'].includes(status);
  };

  const statusTabs = [
    { key: 'all', label: t.common.all, count: stats.total, icon: <Ticket className="w-3.5 h-3.5" /> },
    { key: 'pending', label: t.status.pending, count: stats.pending, icon: <Clock className="w-3.5 h-3.5" /> },
    { key: 'in_progress', label: t.status.inProgress, count: stats.inProgress, icon: <Loader2 className="w-3.5 h-3.5" /> },
    { key: 'resolved', label: t.status.resolved, count: stats.resolved, icon: <CheckCircle2 className="w-3.5 h-3.5" /> },
    { key: 'closed', label: t.status.closed, count: stats.closed, icon: <Circle className="w-3.5 h-3.5" /> },
  ];

  // Filter complaints by status tab (for display)
  const displayedComplaints = useMemo(() => {
    if (statusFilter === 'all') return allComplaints;
    if (statusFilter === 'in_progress') {
      return allComplaints.filter((c) => c.status === 'assigned' || c.status === 'in_progress');
    }
    return allComplaints.filter((c) => c.status === statusFilter);
  }, [allComplaints, statusFilter]);

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Refresh Indicator */}
      {refreshing && (
        <div className="flex items-center justify-center gap-2 py-1">
          <RefreshCw className="w-4 h-4 text-emerald-500 animate-spin" />
          <span className="text-sm text-emerald-600">Refreshing tickets...</span>
        </div>
      )}

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-emerald-800">{t.nav.ticketTracking}</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Track and monitor your support tickets
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Button
            onClick={() => fetchComplaints(true)}
            variant="outline"
            size="sm"
            className="border-emerald-200 text-emerald-700 hover:bg-emerald-50"
            disabled={refreshing}
          >
            <RefreshCw className={`w-3.5 h-3.5 mr-1 ${refreshing ? 'animate-spin' : ''}`} />
            {t.actions.refresh}
          </Button>
        </div>
      </div>

      {/* Track by Ticket Number */}
      <Card className="border-emerald-200 shadow-sm bg-gradient-to-r from-emerald-50 to-white">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <div className="absolute left-3 top-1/2 -translate-y-1/2 w-7 h-7 rounded-md bg-emerald-100 flex items-center justify-center">
                <Ticket className="w-4 h-4 text-emerald-600" />
              </div>
              <Input
                placeholder="Track by Ticket Number (e.g., TK-2025-001)"
                value={ticketNumberSearch}
                onChange={(e) => setTicketNumberSearch(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearchByTicketNumber()}
                className="pl-12 h-11 border-emerald-300 focus:border-emerald-500 focus:ring-emerald-400 bg-white text-sm font-medium"
              />
            </div>
            <Button
              onClick={() => handleSearchByTicketNumber()}
              className="h-11 bg-emerald-600 hover:bg-emerald-700 text-white px-6"
              disabled={searchedTicketLoading}
            >
              {searchedTicketLoading ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : (
                <Search className="w-4 h-4 mr-2" />
              )}
              Track Ticket
            </Button>
          </div>

          {/* Search Result */}
          {searchedTicketError && (
            <div className="mt-3 flex items-center gap-2 text-sm text-red-600 bg-red-50 p-3 rounded-lg border border-red-100">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              {searchedTicketError}
            </div>
          )}
          {searchedTicket && !searchedTicketError && (
            <div className="mt-3 border border-emerald-200 rounded-lg bg-white p-4 shadow-sm">
              <div className="flex items-start justify-between gap-3">
                <div className="flex items-start gap-3 min-w-0">
                  <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-emerald-50 text-emerald-600 flex-shrink-0">
                    {TYPE_ICONS[searchedTicket.complaintType] || <Ticket className="w-5 h-5" />}
                  </div>
                  <div className="min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="font-semibold text-sm text-emerald-800">{searchedTicket.ticketNumber}</span>
                      <Badge variant="outline" className={`text-[11px] px-2 py-0 ${STATUS_COLORS[searchedTicket.status] || ''}`}>
                        {getStatusLabel(searchedTicket.status, t)}
                      </Badge>
                      <Badge variant="secondary" className={`text-[11px] px-2 py-0 ${PRIORITY_COLORS[searchedTicket.priority] || ''}`}>
                        {t.priority[searchedTicket.priority as keyof typeof t.priority] || searchedTicket.priority}
                      </Badge>
                    </div>
                    <p className="text-sm text-gray-600 mt-1 line-clamp-2">{searchedTicket.description}</p>
                    <div className="flex items-center gap-3 mt-1.5 text-xs text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {searchedTicket.area?.name}
                      </span>
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {formatDate(searchedTicket.updatedAt, language)}
                      </span>
                    </div>
                  </div>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => openDetailModal(searchedTicket)}
                  className="flex-shrink-0 border-emerald-200 text-emerald-700 hover:bg-emerald-50"
                >
                  View Details
                </Button>
              </div>
              {/* Mini progress */}
              <div className="mt-3">
                <div className="flex items-center gap-1">
                  {STATUS_FLOW.map((step, idx) => {
                    const stepIdx = STATUS_FLOW.indexOf(searchedTicket.status);
                    const isCompleted = idx <= (stepIdx >= 0 ? stepIdx : 0);
                    return (
                      <div key={step} className="flex items-center flex-1">
                        <div
                          className={`w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold ${
                            isCompleted ? 'bg-emerald-500 text-white' : 'bg-gray-100 text-gray-400'
                          }`}
                        >
                          {isCompleted ? '✓' : idx + 1}
                        </div>
                        {idx < STATUS_FLOW.length - 1 && (
                          <div className={`h-0.5 flex-1 ${isCompleted && idx < (stepIdx >= 0 ? stepIdx : 0) ? 'bg-emerald-500' : 'bg-gray-200'}`} />
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* User Profile Summary Card */}
      {currentUser && (
        <Card className="border-emerald-100 shadow-sm bg-gradient-to-r from-emerald-50/50 to-white">
          <CardContent className="p-4">
            <div className="flex items-center gap-4">
              <Avatar className="h-12 w-12 border-2 border-emerald-200">
                <AvatarFallback className="bg-emerald-600 text-white font-semibold">
                  {currentUser.name?.charAt(0)?.toUpperCase() || 'U'}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1 min-w-0">
                <h3 className="font-semibold text-emerald-900 truncate">{currentUser.name}</h3>
                <p className="text-xs text-muted-foreground truncate">{currentUser.email}</p>
              </div>
              <div className="flex gap-4 sm:gap-6 flex-shrink-0">
                <div className="text-center">
                  <p className="text-lg font-bold text-emerald-800">{stats.total}</p>
                  <p className="text-[10px] text-muted-foreground uppercase tracking-wider">Total</p>
                </div>
                <div className="text-center">
                  <p className="text-lg font-bold text-amber-700">{userProfile.activeCount}</p>
                  <p className="text-[10px] text-muted-foreground uppercase tracking-wider">Active</p>
                </div>
                {userProfile.lastDate && (
                  <div className="text-center hidden sm:block">
                    <p className="text-sm font-semibold text-emerald-700">{formatDateShort(userProfile.lastDate.toISOString(), language)}</p>
                    <p className="text-[10px] text-muted-foreground uppercase tracking-wider">Last Ticket</p>
                  </div>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Stats Cards */}
      <div className="grid grid-cols-3 sm:grid-cols-5 gap-2 sm:gap-3">
        <Card className="border-emerald-100 shadow-sm">
          <CardContent className="p-2 sm:p-3 flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-emerald-50 flex items-center justify-center flex-shrink-0">
              <Ticket className="w-4 h-4 sm:w-5 sm:h-5 text-emerald-600" />
            </div>
            <div>
              <p className="text-lg sm:text-2xl font-bold text-emerald-800">{stats.total}</p>
              <p className="text-[9px] sm:text-[11px] text-muted-foreground">{t.common.total}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="border-amber-100 shadow-sm">
          <CardContent className="p-2 sm:p-3 flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-amber-50 flex items-center justify-center flex-shrink-0">
              <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600" />
            </div>
            <div>
              <p className="text-lg sm:text-2xl font-bold text-amber-800">{stats.pending}</p>
              <p className="text-[9px] sm:text-[11px] text-muted-foreground">{t.status.pending}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="border-purple-100 shadow-sm">
          <CardContent className="p-2 sm:p-3 flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-purple-50 flex items-center justify-center flex-shrink-0">
              <Loader2 className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" />
            </div>
            <div>
              <p className="text-lg sm:text-2xl font-bold text-purple-800">{stats.inProgress}</p>
              <p className="text-[9px] sm:text-[11px] text-muted-foreground">{t.status.inProgress}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="border-emerald-100 shadow-sm">
          <CardContent className="p-2 sm:p-3 flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-emerald-50 flex items-center justify-center flex-shrink-0">
              <CheckCircle2 className="w-4 h-4 sm:w-5 sm:h-5 text-emerald-600" />
            </div>
            <div>
              <p className="text-lg sm:text-2xl font-bold text-emerald-800">{stats.resolved}</p>
              <p className="text-[9px] sm:text-[11px] text-muted-foreground">{t.status.resolved}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="border-gray-100 shadow-sm col-span-3 sm:col-span-1">
          <CardContent className="p-2 sm:p-3 flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-gray-50 flex items-center justify-center flex-shrink-0">
              <Circle className="w-4 h-4 sm:w-5 sm:h-5 text-gray-500" />
            </div>
            <div>
              <p className="text-lg sm:text-2xl font-bold text-gray-700">{stats.closed}</p>
              <p className="text-[9px] sm:text-[11px] text-muted-foreground">{t.status.closed}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Status Filter Tabs */}
      <div className="flex gap-1 sm:gap-1.5 overflow-x-auto pb-1 -mx-1 px-1 scrollbar-none">
        {statusTabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setStatusFilter(tab.key)}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all ${
              statusFilter === tab.key
                ? 'bg-emerald-600 text-white shadow-sm'
                : 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
            }`}
          >
            {tab.icon}
            {tab.label}
            <span
              className={`ml-0.5 px-1.5 py-0 rounded-full text-[10px] font-bold ${
                statusFilter === tab.key
                  ? 'bg-white/20 text-white'
                  : 'bg-emerald-100 text-emerald-800'
              }`}
            >
              {tab.count}
            </span>
          </button>
        ))}
      </div>

      {/* Search Bar */}
      <Card className="border-emerald-100 shadow-sm">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-emerald-400" />
              <Input
                placeholder="Search by ticket number, description, name, phone..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-44 border-emerald-200">
                <Filter className="w-4 h-4 mr-2 text-emerald-500" />
                <SelectValue placeholder="Filter status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t.common.all}</SelectItem>
                <SelectItem value="pending">{t.status.pending}</SelectItem>
                <SelectItem value="assigned">{t.status.assigned}</SelectItem>
                <SelectItem value="in_progress">{t.status.inProgress}</SelectItem>
                <SelectItem value="diagnosed">{t.status.diagnosed}</SelectItem>
                <SelectItem value="resolved">{t.status.resolved}</SelectItem>
                <SelectItem value="closed">{t.status.closed}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Ticket List */}
      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
          <span className="ml-3 text-emerald-600">{t.common.loading}</span>
        </div>
      ) : displayedComplaints.length === 0 ? (
        /* Enhanced Empty State */
        <Card className="border-emerald-100 shadow-sm">
          <CardContent className="flex flex-col items-center justify-center py-16 px-6 text-center">
            <div className="w-20 h-20 rounded-full bg-emerald-50 flex items-center justify-center mb-5">
              <Ticket className="w-10 h-10 text-emerald-300" />
            </div>
            <h3 className="text-lg font-semibold text-emerald-800 mb-2">
              You haven't submitted any tickets yet
            </h3>
            <p className="text-sm text-muted-foreground max-w-md mb-6">
              Start by raising a complaint through our AI assistant. It will guide you through the process step by step.
            </p>
            <Button
              onClick={() => setView('ai-assistant')}
              className="bg-emerald-600 hover:bg-emerald-700 text-white px-6 h-11"
            >
              <Sparkles className="w-4 h-4 mr-2" />
              Raise a Complaint
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-3">
          {displayedComplaints.map((complaint) => {
            const isExpanded = expandedTicket === complaint.id;
            const statusStep = getStatusStepIndex(complaint.status);
            const active = isActive(complaint.status);

            return (
              <Card
                key={complaint.id}
                className={`border shadow-sm transition-all duration-200 ${
                  isExpanded
                    ? 'border-emerald-300 shadow-md ring-1 ring-emerald-200'
                    : 'border-emerald-100 hover:border-emerald-200 hover:shadow'
                }`}
              >
                {/* Ticket Card Header */}
                <div className="w-full text-left p-4">
                  <div className="flex items-start justify-between gap-3">
                    <button
                      onClick={() => toggleTicket(complaint.id)}
                      className="flex items-start gap-3 min-w-0 text-left flex-1"
                    >
                      <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-emerald-50 text-emerald-600 flex-shrink-0">
                        {TYPE_ICONS[complaint.complaintType] || <Ticket className="w-5 h-5" />}
                      </div>
                      <div className="min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="font-semibold text-sm text-emerald-800">
                            {complaint.ticketNumber}
                          </span>
                          <Badge
                            variant="outline"
                            className={`text-[11px] px-2 py-0 ${STATUS_COLORS[complaint.status] || ''}`}
                          >
                            {active && (
                              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 mr-1 animate-pulse-green inline-block" />
                            )}
                            {getStatusLabel(complaint.status, t)}
                          </Badge>
                          <Badge
                            variant="secondary"
                            className={`text-[11px] px-2 py-0 ${PRIORITY_COLORS[complaint.priority] || ''}`}
                          >
                            {t.priority[complaint.priority as keyof typeof t.priority] || complaint.priority}
                          </Badge>
                        </div>
                        <p className="text-sm text-gray-600 mt-1 line-clamp-1">
                          {complaint.description}
                        </p>
                        <div className="flex items-center gap-3 mt-1.5 text-xs text-muted-foreground">
                          <span className="flex items-center gap-1">
                            {TYPE_ICONS[complaint.complaintType]}
                            {t.complaint[`type${complaint.complaintType.charAt(0).toUpperCase() + complaint.complaintType.slice(1)}` as keyof typeof t.complaint] || complaint.complaintType}
                          </span>
                          <span className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            {complaint.area?.name}
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            {formatDate(complaint.updatedAt, language)}
                          </span>
                        </div>
                      </div>
                    </button>
                    <div className="flex items-center gap-1 flex-shrink-0">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          openDetailModal(complaint);
                        }}
                        className="text-emerald-600 hover:text-emerald-800 hover:bg-emerald-50 h-8 px-2"
                      >
                        <FileText className="w-4 h-4" />
                      </Button>
                      <button
                        onClick={() => toggleTicket(complaint.id)}
                        className="h-8 w-8 flex items-center justify-center rounded-md hover:bg-emerald-50 transition-colors"
                      >
                        {isExpanded ? (
                          <ChevronDown className="w-5 h-5 text-emerald-500" />
                        ) : (
                          <ChevronRight className="w-5 h-5 text-emerald-400" />
                        )}
                      </button>
                    </div>
                  </div>
                </div>

                {/* Expanded Details */}
                {isExpanded && (
                  <div className="border-t border-emerald-100 animate-fade-in">
                    {detailsLoading ? (
                      <div className="flex items-center justify-center py-8">
                        <Loader2 className="w-6 h-6 text-emerald-500 animate-spin" />
                      </div>
                    ) : expandedDetails ? (
                      <div className="p-4 space-y-5">
                        {/* Status Flow Visualization */}
                        <div>
                          <h4 className="text-sm font-semibold text-emerald-800 mb-3">Status Progress</h4>
                          <div className="flex items-center gap-0 overflow-x-auto pb-2">
                            {STATUS_FLOW.map((step, idx) => {
                              const isCompleted = idx <= statusStep;
                              const isCurrent = idx === statusStep;
                              return (
                                <React.Fragment key={step}>
                                  <div className="flex flex-col items-center min-w-[72px]">
                                    <div
                                      className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all ${
                                        isCompleted
                                          ? isCurrent && active
                                            ? 'bg-emerald-500 text-white animate-pulse-green'
                                            : 'bg-emerald-500 text-white'
                                          : 'bg-gray-100 text-gray-400'
                                      }`}
                                    >
                                      {isCompleted ? '✓' : idx + 1}
                                    </div>
                                    <span
                                      className={`text-[10px] mt-1 text-center whitespace-nowrap ${
                                        isCompleted ? 'text-emerald-700 font-semibold' : 'text-gray-400'
                                      }`}
                                    >
                                      {getStatusLabel(step, t)}
                                    </span>
                                  </div>
                                  {idx < STATUS_FLOW.length - 1 && (
                                    <div
                                      className={`h-0.5 w-8 sm:w-12 flex-shrink-0 ${
                                        idx < statusStep ? 'bg-emerald-500' : 'bg-gray-200'
                                      }`}
                                    />
                                  )}
                                </React.Fragment>
                              );
                            })}
                          </div>
                        </div>

                        <Separator className="bg-emerald-100" />

                        {/* Details Grid */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                          <div className="space-y-3">
                            <div>
                              <span className="text-xs font-medium text-emerald-600 uppercase tracking-wider">
                                {t.complaint.description}
                              </span>
                              <p className="text-sm text-gray-700 mt-1">
                                {expandedDetails.description}
                              </p>
                            </div>
                            {expandedDetails.resolution && (
                              <div>
                                <span className="text-xs font-medium text-emerald-600 uppercase tracking-wider">
                                  {t.complaint.resolution}
                                </span>
                                <p className="text-sm text-gray-700 mt-1 bg-emerald-50 p-3 rounded-lg border border-emerald-100">
                                  {expandedDetails.resolution}
                                </p>
                              </div>
                            )}
                          </div>
                          <div className="space-y-2">
                            <div className="flex items-center gap-2 text-sm">
                              <User className="w-4 h-4 text-emerald-500" />
                              <span className="text-muted-foreground">{t.complaint.assignedTo}:</span>
                              <span className="font-medium text-emerald-800">
                                {expandedDetails.assignedEngineer?.name || expandedDetails.assignedHOD?.name || 'Unassigned'}
                              </span>
                            </div>
                            <div className="flex items-center gap-2 text-sm">
                              <MapPin className="w-4 h-4 text-emerald-500" />
                              <span className="text-muted-foreground">{t.complaint.area}:</span>
                              <span className="font-medium">{expandedDetails.area?.name}</span>
                            </div>
                            <div className="flex items-center gap-2 text-sm">
                              <Clock className="w-4 h-4 text-emerald-500" />
                              <span className="text-muted-foreground">{t.complaint.createdAt}:</span>
                              <span className="font-medium">{formatDate(expandedDetails.createdAt, language)}</span>
                            </div>
                            <div className="flex items-center gap-2 text-sm">
                              <MessageSquare className="w-4 h-4 text-emerald-500" />
                              <span className="text-muted-foreground">WhatsApp:</span>
                              <Badge variant="outline" className="text-[11px] bg-green-50 text-green-700 border-green-200">
                                Notifications Active
                              </Badge>
                            </div>
                          </div>
                        </div>

                        <Separator className="bg-emerald-100" />

                        {/* Timeline */}
                        <div>
                          <h4 className="text-sm font-semibold text-emerald-800 mb-3">
                            {t.complaint.timeline}
                          </h4>
                          {expandedDetails.updates && expandedDetails.updates.length > 0 ? (
                            <div className="space-y-0">
                              {expandedDetails.updates
                                .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                                .map((update, idx) => (
                                  <div key={update.id} className="flex gap-3">
                                    <div className="flex flex-col items-center">
                                      <div className="w-8 h-8 rounded-full bg-white border-2 border-emerald-200 flex items-center justify-center flex-shrink-0">
                                        {getUpdateIcon(update.updateType)}
                                      </div>
                                      {idx < (expandedDetails.updates?.length || 0) - 1 && (
                                        <div className="w-0.5 h-full bg-emerald-100 my-0.5" />
                                      )}
                                    </div>
                                    <div className="pb-4 min-w-0">
                                      <p className="text-sm font-medium text-emerald-800">
                                        {update.title}
                                      </p>
                                      <p className="text-xs text-gray-600 mt-0.5">
                                        {update.description}
                                      </p>
                                      <p className="text-[11px] text-muted-foreground mt-1">
                                        {formatDate(update.createdAt, language)}
                                      </p>
                                    </div>
                                  </div>
                                ))}
                            </div>
                          ) : (
                            <p className="text-sm text-muted-foreground">{t.common.noData}</p>
                          )}
                        </div>

                        {/* View Full Detail Button */}
                        <div className="flex justify-center pt-2">
                          <Button
                            onClick={() => openDetailModal(expandedDetails)}
                            className="bg-emerald-600 hover:bg-emerald-700 text-white"
                          >
                            <FileText className="w-4 h-4 mr-2" />
                            View Full Details
                          </Button>
                        </div>
                      </div>
                    ) : null}
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}

      {/* Ticket Detail Modal */}
      <TicketDetailModal
        complaint={detailModalComplaint}
        open={detailModalOpen}
        onClose={() => {
          setDetailModalOpen(false);
          setDetailModalComplaint(null);
        }}
        language={language}
        t={t}
        onSearchTicket={handleTrackFromModal}
      />
    </div>
  );
}
