'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { useStore } from '@/lib/store';
import {
  ListTodo, Loader2, Eye, CheckCircle2, MessageSquarePlus,
  Clock, AlertCircle, User, ArrowRight, ArrowLeft, ArrowUp, ArrowDown,
  Users, BarChart3, Filter, Download, Calendar,
  TrendingUp, AlertTriangle, ChevronRight,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/use-toast';
import { authFetch } from '@/lib/api';

interface TaskComplaint {
  id: string;
  ticketNumber: string;
  clientName: string;
  clientPhone: string;
  complaintType: string;
  priority: string;
  status: string;
  description: string;
  area: { id: string; name: string; code: string } | null;
  assignedHOD: { id: string; name: string; email: string } | null;
  assignedEngineer: { id: string; name: string; email: string } | null;
  resolution?: string;
  createdAt: string;
  updatedAt: string;
  updates?: Array<{
    id: string;
    updateType: string;
    title: string;
    description: string;
    updatedBy: string;
    createdAt: string;
  }>;
}

interface UserOption {
  id: string;
  name: string;
  role: string;
}

const statusColor = (s: string) => {
  const m: Record<string, string> = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-950/30 dark:text-yellow-300',
    assigned: 'bg-blue-100 text-blue-800 dark:bg-blue-950/30 dark:text-blue-300',
    in_progress: 'bg-orange-100 text-orange-800 dark:bg-orange-950/30 dark:text-orange-300',
    resolved: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-300',
    closed: 'bg-gray-100 text-gray-800 dark:bg-gray-950/30 dark:text-gray-300',
  };
  return m[s] || '';
};

const priorityColor = (p: string) => {
  const m: Record<string, string> = {
    low: 'bg-gray-100 text-gray-800 dark:bg-gray-950/30 dark:text-gray-300',
    medium: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-950/30 dark:text-yellow-300',
    high: 'bg-orange-100 text-orange-800 dark:bg-orange-950/30 dark:text-orange-300',
    critical: 'bg-red-100 text-red-800 dark:bg-red-950/30 dark:text-red-300',
  };
  return m[p] || '';
};

const priorityBarColor = (p: string) => {
  const m: Record<string, string> = {
    low: 'bg-gray-400',
    medium: 'bg-yellow-400',
    high: 'bg-orange-500',
    critical: 'bg-red-500',
  };
  return m[p] || 'bg-gray-300';
};

const KANBAN_COLUMNS = [
  { key: 'pending', label: 'Pending', color: 'border-yellow-400' },
  { key: 'assigned', label: 'Assigned', color: 'border-blue-400' },
  { key: 'in_progress', label: 'In Progress', color: 'border-orange-400' },
  { key: 'resolved', label: 'Resolved', color: 'border-emerald-400' },
];

function TaskCard({ task, onClick, onMoveLeft, onMoveRight, showMoveButtons }: {
  task: TaskComplaint;
  onClick: () => void;
  onMoveLeft?: () => void;
  onMoveRight?: () => void;
  showMoveButtons?: boolean;
}) {
  return (
    <Card
      className="cursor-pointer hover:shadow-md transition-shadow border-l-4"
      style={{ borderLeftColor: task.status === 'pending' ? '#eab308' : task.status === 'assigned' ? '#3b82f6' : task.status === 'in_progress' ? '#f97316' : '#10b981' }}
    >
      <CardContent className="p-3 space-y-2">
        <div className="flex items-center justify-between">
          <span className="text-xs font-mono font-bold text-emerald-600">{task.ticketNumber}</span>
          <span className={`inline-flex items-center px-1.5 py-0.5 rounded-full text-[9px] font-medium ${priorityColor(task.priority)}`}>
            {task.priority}
          </span>
        </div>
        <p className="text-xs font-medium truncate">{task.clientName}</p>
        <p className="text-[10px] text-muted-foreground line-clamp-2">{task.description}</p>
        <div className="flex items-center justify-between">
          <span className={`inline-flex items-center px-1.5 py-0.5 rounded-full text-[9px] font-medium ${statusColor(task.status)}`}>
            {task.status.replace(/_/g, ' ')}
          </span>
          <span className="text-[9px] text-muted-foreground">{new Date(task.createdAt).toLocaleDateString()}</span>
        </div>
        {task.assignedEngineer && (
          <div className="flex items-center gap-1 text-[10px] text-muted-foreground">
            <User className="w-3 h-3" /> {task.assignedEngineer.name}
          </div>
        )}
        {showMoveButtons && (
          <div className="flex items-center gap-1 pt-1 border-t">
            {onMoveLeft && (
              <Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={(e) => { e.stopPropagation(); onMoveLeft(); }}>
                <ArrowLeft className="w-3 h-3" />
              </Button>
            )}
            <Button variant="ghost" size="sm" className="h-6 px-2 text-[10px] flex-1" onClick={onClick}>
              <Eye className="w-3 h-3 mr-1" /> View
            </Button>
            {onMoveRight && (
              <Button variant="ghost" size="sm" className="h-6 px-2 text-[10px]" onClick={(e) => { e.stopPropagation(); onMoveRight(); }}>
                <ArrowRight className="w-3 h-3" />
              </Button>
            )}
          </div>
        )}
        {!showMoveButtons && (
          <div className="pt-1 border-t">
            <Button variant="ghost" size="sm" className="h-6 px-2 text-[10px] w-full" onClick={onClick}>
              <Eye className="w-3 h-3 mr-1" /> View Details
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

export default function TaskManagement({ mode = 'my-tasks' }: { mode?: string }) {
  const { t } = useTranslation();
  const currentUser = useStore((s) => s.currentUser);
  const { toast } = useToast();

  const [complaints, setComplaints] = useState<TaskComplaint[]>([]);
  const [users, setUsers] = useState<UserOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedTask, setSelectedTask] = useState<TaskComplaint | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [actionDialog, setActionDialog] = useState<string | null>(null);
  const [actionNote, setActionNote] = useState('');
  const [actionResolution, setActionResolution] = useState('');
  const [actionLoading, setActionLoading] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState('');
  const [search, setSearch] = useState('');

  // Debounced search to avoid excessive API calls
  const [debouncedSearch, setDebouncedSearch] = useState('');
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 400);
    return () => clearTimeout(timer);
  }, [search]);

  // Filters
  const [filterPriority, setFilterPriority] = useState('');
  const [filterType, setFilterType] = useState('');
  const [filterAssignee, setFilterAssignee] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');

  // Extract primitive values from currentUser to avoid object reference in deps
  const currentUserId = currentUser?.id;
  const currentUserRole = currentUser?.role;

  const fetchComplaints = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      params.set('limit', '100');
      if (mode === 'my-tasks' && currentUserId) {
        if (currentUserRole === 'service_engineer') {
          params.set('assignedEngineerId', currentUserId);
        } else if (currentUserRole === 'head_of_department') {
          params.set('assignedHODId', currentUserId);
        }
      }
      if (selectedUserId && mode === 'user-tasks') {
        params.set('assignedEngineerId', selectedUserId);
      }
      if (debouncedSearch) params.set('search', debouncedSearch);

      const res = await authFetch(`/api/complaints?${params}`);
      if (res.ok) {
        const data = await res.json();
        setComplaints(data.complaints || []);
      }
    } catch (err) {
      console.error('Fetch tasks error:', err);
    } finally {
      setLoading(false);
    }
  }, [mode, currentUserId, currentUserRole, selectedUserId, debouncedSearch]);

  const fetchUsers = useCallback(async () => {
    try {
      const res = await authFetch('/api/users?limit=100');
      if (res.ok) {
        const data = await res.json();
        setUsers((data.users || []).map((u: { id: string; name: string; role: string }) => ({
          id: u.id,
          name: u.name,
          role: u.role,
        })));
      }
    } catch (err) {
      console.error('Fetch users error:', err);
    }
  }, []);

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

  const openDetail = async (task: TaskComplaint) => {
    setSelectedTask(task);
    setDetailOpen(true);
  };

  const handleAction = async () => {
    if (!selectedTask || !actionDialog) return;
    setActionLoading(true);
    try {
      if (actionDialog === 'accept') {
        const res = await authFetch(`/api/complaints/${selectedTask.id}`, {
          method: 'POST',
          body: JSON.stringify({ action: 'forward_to_engineer', updatedBy: currentUser?.name || 'user' }),
        });
        if (res.ok) toast({ title: 'Task accepted' });
      } else if (actionDialog === 'update-status') {
        const res = await authFetch(`/api/complaints/${selectedTask.id}`, {
          method: 'PUT',
          body: JSON.stringify({ status: 'in_progress', updatedBy: currentUser?.name || 'user' }),
        });
        if (res.ok) toast({ title: 'Status updated to In Progress' });
      } else if (actionDialog === 'note') {
        await authFetch(`/api/complaints/${selectedTask.id}`, {
          method: 'POST',
          body: JSON.stringify({
            action: 'add_note',
            noteTitle: 'Task Note',
            noteDescription: actionNote,
            updatedBy: currentUser?.name || 'user',
          }),
        });
        toast({ title: 'Note added' });
      } else if (actionDialog === 'resolve') {
        const res = await authFetch(`/api/complaints/${selectedTask.id}`, {
          method: 'POST',
          body: JSON.stringify({
            action: 'resolve',
            resolution: actionResolution,
            updatedBy: currentUser?.name || 'user',
          }),
        });
        if (res.ok) toast({ title: 'Task resolved' });
      }
      setActionDialog(null);
      setActionNote('');
      setActionResolution('');
      fetchComplaints();
    } catch (err) {
      console.error('Action error:', err);
    } finally {
      setActionLoading(false);
    }
  };

  /* ---------- Move task between kanban columns ---------- */
  const moveTask = async (taskId: string, newStatus: string) => {
    try {
      const res = await authFetch(`/api/complaints/${taskId}`, {
        method: 'PUT',
        body: JSON.stringify({ status: newStatus, updatedBy: currentUser?.name || 'user' }),
      });
      if (res.ok) {
        toast({ title: `Task moved to ${newStatus.replace(/_/g, ' ')}` });
        fetchComplaints();
      }
    } catch (err) {
      console.error('Move task error:', err);
    }
  };

  /* ---------- Filtered complaints ---------- */
  const filteredComplaints = complaints.filter(c => {
    if (filterPriority && c.priority !== filterPriority) return false;
    if (filterType && c.complaintType !== filterType) return false;
    if (filterAssignee) {
      const assigneeName = c.assignedEngineer?.name || c.assignedHOD?.name || '';
      if (!assigneeName.toLowerCase().includes(filterAssignee.toLowerCase())) return false;
    }
    if (dateFrom && new Date(c.createdAt) < new Date(dateFrom)) return false;
    if (dateTo && new Date(c.createdAt) > new Date(dateTo + 'T23:59:59')) return false;
    return true;
  });

  /* ---------- Statistics ---------- */
  const stats = {
    total: filteredComplaints.length,
    pending: filteredComplaints.filter(c => c.status === 'pending').length,
    assigned: filteredComplaints.filter(c => c.status === 'assigned').length,
    inProgress: filteredComplaints.filter(c => c.status === 'in_progress').length,
    resolved: filteredComplaints.filter(c => c.status === 'resolved').length,
    closed: filteredComplaints.filter(c => c.status === 'closed').length,
    overdue: filteredComplaints.filter(c => {
      if (c.status === 'resolved' || c.status === 'closed') return false;
      const created = new Date(c.createdAt);
      const now = new Date();
      const daysDiff = (now.getTime() - created.getTime()) / (1000 * 60 * 60 * 24);
      return daysDiff > 7;
    }).length,
  };

  /* ---------- Priority distribution ---------- */
  const priorityDistribution = {
    low: filteredComplaints.filter(c => c.priority === 'low').length,
    medium: filteredComplaints.filter(c => c.priority === 'medium').length,
    high: filteredComplaints.filter(c => c.priority === 'high').length,
    critical: filteredComplaints.filter(c => c.priority === 'critical').length,
  };
  const maxPriorityCount = Math.max(...Object.values(priorityDistribution), 1);

  /* ---------- Export CSV ---------- */
  const exportCSV = () => {
    const headers = ['Ticket#', 'Client', 'Phone', 'Type', 'Priority', 'Status', 'Assigned Engineer', 'Assigned HOD', 'Created', 'Description'];
    const rows = filteredComplaints.map(c => [
      c.ticketNumber,
      c.clientName,
      c.clientPhone,
      c.complaintType,
      c.priority,
      c.status,
      c.assignedEngineer?.name || '',
      c.assignedHOD?.name || '',
      new Date(c.createdAt).toLocaleDateString(),
      `"${c.description.replace(/"/g, '""')}"`,
    ]);
    const csvContent = [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `tasks_export_${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    toast({ title: 'Tasks exported', description: `${filteredComplaints.length} tasks exported as CSV` });
  };

  /* ---------- Timeline entries ---------- */
  const timelineEntries = filteredComplaints
    .flatMap(c => (c.updates || []).map(u => ({ ...u, ticketNumber: c.ticketNumber, complaintId: c.id })))
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    .slice(0, 50);

  const getTitle = () => {
    switch (mode) {
      case 'my-tasks': return 'My Tasks';
      case 'all-tasks': return 'All Tasks';
      case 'task-board': return 'Task Board';
      case 'user-tasks': return 'User-wise Tasks';
      case 'task-statistics': return 'Task Statistics';
      case 'task-timeline': return 'Task Timeline';
      default: return 'Task Management';
    }
  };

  const engineers = users.filter(u => u.role === 'service_engineer' || u.role === 'head_of_department');

  if (loading) {
    return <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-emerald-600" /></div>;
  }

  return (
    <div className="space-y-4 animate-fade-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <ListTodo className="w-6 h-6 text-emerald-600" />
            {getTitle()}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {filteredComplaints.length} task(s) found
          </p>
        </div>
        <div className="flex gap-2 items-center flex-wrap">
          <div className="relative">
            <Input
              placeholder="Search tasks..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="h-9 w-48"
            />
          </div>
          {mode === 'user-tasks' && (
            <Select value={selectedUserId} onValueChange={setSelectedUserId}>
              <SelectTrigger className="w-48 h-9">
                <SelectValue placeholder="Filter by user" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Users</SelectItem>
                {engineers.map(u => (
                  <SelectItem key={u.id} value={u.id}>{u.name} ({u.role.replace(/_/g, ' ')})</SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
          <Button variant="outline" size="sm" onClick={exportCSV} className="h-9">
            <Download className="w-4 h-4 mr-1" /> Export
          </Button>
        </div>
      </div>

      {/* Task Statistics Header - shown on all modes */}
      <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-2">
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-foreground">{stats.total}</p>
            <p className="text-[10px] text-muted-foreground">Total</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-yellow-600">{stats.pending}</p>
            <p className="text-[10px] text-muted-foreground">Pending</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-blue-600">{stats.assigned}</p>
            <p className="text-[10px] text-muted-foreground">Assigned</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-orange-600">{stats.inProgress}</p>
            <p className="text-[10px] text-muted-foreground">In Progress</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-emerald-600">{stats.resolved}</p>
            <p className="text-[10px] text-muted-foreground">Resolved</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-gray-600">{stats.closed}</p>
            <p className="text-[10px] text-muted-foreground">Closed</p>
          </div>
        </Card>
        <Card className="p-3">
          <div className="text-center">
            <p className="text-lg font-bold text-red-600">{stats.overdue}</p>
            <p className="text-[10px] text-muted-foreground">Overdue</p>
          </div>
        </Card>
      </div>

      {/* Priority Distribution - shown on all modes */}
      <Card>
        <CardContent className="p-4">
          <h3 className="text-xs font-semibold mb-3 flex items-center gap-1.5">
            <BarChart3 className="w-3.5 h-3.5 text-emerald-600" /> Priority Distribution
          </h3>
          <div className="space-y-2">
            {(['critical', 'high', 'medium', 'low'] as const).map(priority => (
              <div key={priority} className="flex items-center gap-2">
                <span className={`text-[10px] font-medium w-14 text-right capitalize ${priority === 'critical' ? 'text-red-600' : priority === 'high' ? 'text-orange-600' : priority === 'medium' ? 'text-yellow-600' : 'text-gray-600'}`}>
                  {priority}
                </span>
                <div className="flex-1 bg-muted rounded-full h-4 overflow-hidden">
                  <div
                    className={`h-full rounded-full ${priorityBarColor(priority)} transition-all duration-500`}
                    style={{ width: `${(priorityDistribution[priority] / maxPriorityCount) * 100}%` }}
                  />
                </div>
                <span className="text-[10px] font-mono text-muted-foreground w-6">{priorityDistribution[priority]}</span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Task Filters */}
      <Card>
        <CardContent className="p-3">
          <div className="flex flex-wrap gap-2 items-center">
            <Filter className="w-4 h-4 text-muted-foreground flex-shrink-0" />
            <Select value={filterPriority} onValueChange={setFilterPriority}>
              <SelectTrigger className="w-[120px] h-8 text-xs">
                <SelectValue placeholder="Priority" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Priority</SelectItem>
                <SelectItem value="low">Low</SelectItem>
                <SelectItem value="medium">Medium</SelectItem>
                <SelectItem value="high">High</SelectItem>
                <SelectItem value="critical">Critical</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterType} onValueChange={setFilterType}>
              <SelectTrigger className="w-[120px] h-8 text-xs">
                <SelectValue placeholder="Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="hardware">Hardware</SelectItem>
                <SelectItem value="software">Software</SelectItem>
                <SelectItem value="network">Network</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
            <Input
              placeholder="Assignee..."
              value={filterAssignee}
              onChange={(e) => setFilterAssignee(e.target.value)}
              className="h-8 w-32 text-xs"
            />
            <div className="flex items-center gap-1">
              <Calendar className="w-3.5 h-3.5 text-muted-foreground" />
              <Input
                type="date"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                className="h-8 w-[130px] text-xs"
              />
              <span className="text-xs text-muted-foreground">to</span>
              <Input
                type="date"
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
                className="h-8 w-[130px] text-xs"
              />
            </div>
            {(filterPriority || filterType || filterAssignee || dateFrom || dateTo) && (
              <Button variant="ghost" size="sm" className="h-8 text-xs" onClick={() => {
                setFilterPriority('');
                setFilterType('');
                setFilterAssignee('');
                setDateFrom('');
                setDateTo('');
              }}>
                Clear Filters
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Task Statistics Mode */}
      {mode === 'task-statistics' && (
        <div className="space-y-4">
          {/* Status Breakdown */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-emerald-600" /> Status Breakdown
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {[
                  { label: 'Pending', count: stats.pending, total: stats.total, color: 'bg-yellow-500', textColor: 'text-yellow-700' },
                  { label: 'Assigned', count: stats.assigned, total: stats.total, color: 'bg-blue-500', textColor: 'text-blue-700' },
                  { label: 'In Progress', count: stats.inProgress, total: stats.total, color: 'bg-orange-500', textColor: 'text-orange-700' },
                  { label: 'Resolved', count: stats.resolved, total: stats.total, color: 'bg-emerald-500', textColor: 'text-emerald-700' },
                  { label: 'Closed', count: stats.closed, total: stats.total, color: 'bg-gray-500', textColor: 'text-gray-700' },
                  { label: 'Overdue', count: stats.overdue, total: stats.total, color: 'bg-red-500', textColor: 'text-red-700' },
                ].map(item => (
                  <div key={item.label} className="bg-muted/50 rounded-lg p-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className={`text-sm font-medium ${item.textColor}`}>{item.label}</span>
                      <span className="text-lg font-bold">{item.count}</span>
                    </div>
                    <div className="w-full bg-muted rounded-full h-2.5">
                      <div
                        className={`h-full rounded-full ${item.color} transition-all`}
                        style={{ width: `${item.total > 0 ? (item.count / item.total) * 100 : 0}%` }}
                      />
                    </div>
                    <p className="text-[10px] text-muted-foreground mt-1">
                      {item.total > 0 ? Math.round((item.count / item.total) * 100) : 0}% of total
                    </p>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Type distribution */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm">Complaint Type Distribution</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {(['hardware', 'software', 'network', 'other'] as const).map(type => {
                  const count = filteredComplaints.filter(c => c.complaintType === type).length;
                  return (
                    <div key={type} className="bg-muted/50 rounded-lg p-3 text-center">
                      <p className="text-xl font-bold capitalize">{count}</p>
                      <p className="text-xs text-muted-foreground capitalize">{type}</p>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Task Timeline Mode */}
      {mode === 'task-timeline' && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm flex items-center gap-2">
              <Clock className="w-4 h-4 text-emerald-600" /> Recent Task Updates
            </CardTitle>
            <CardDescription>Latest updates across all tasks</CardDescription>
          </CardHeader>
          <CardContent>
            {timelineEntries.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Clock className="w-10 h-10 mx-auto mb-2 opacity-20" />
                <p className="text-sm">No recent updates</p>
              </div>
            ) : (
              <ScrollArea className="max-h-[60vh]">
                <div className="space-y-0">
                  {timelineEntries.map((entry, idx) => (
                    <div key={entry.id} className="flex gap-3 pb-4">
                      <div className="flex flex-col items-center">
                        <div className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${
                          entry.updateType === 'status_change' ? 'bg-blue-500' :
                          entry.updateType === 'resolution' ? 'bg-emerald-500' :
                          entry.updateType === 'note' ? 'bg-yellow-500' :
                          'bg-gray-400'
                        }`} />
                        {idx < timelineEntries.length - 1 && (
                          <div className="w-0.5 flex-1 bg-muted mt-1" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0 pb-2">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-xs font-mono font-bold text-emerald-600">{entry.ticketNumber}</span>
                          <span className="text-xs font-medium">{entry.title}</span>
                        </div>
                        {entry.description && (
                          <p className="text-[11px] text-muted-foreground mt-0.5 line-clamp-2">{entry.description}</p>
                        )}
                        <p className="text-[10px] text-muted-foreground mt-1">
                          {new Date(entry.createdAt).toLocaleString()} • by {entry.updatedBy}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>
            )}
          </CardContent>
        </Card>
      )}

      {/* Task Board (Kanban) */}
      {mode === 'task-board' ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {KANBAN_COLUMNS.map((col, colIdx) => {
            const columnTasks = filteredComplaints.filter(c => c.status === col.key);
            return (
              <div key={col.key} className={`border-t-4 ${col.color} rounded-lg bg-muted/30`}>
                <div className="p-3 border-b bg-card/50">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-semibold">{col.label}</span>
                    <Badge variant="secondary" className="text-[10px] ml-auto">{columnTasks.length}</Badge>
                  </div>
                </div>
                <ScrollArea className="h-[50vh] p-2">
                  <div className="space-y-2">
                    {columnTasks.length === 0 ? (
                      <p className="text-xs text-muted-foreground text-center py-8">No tasks</p>
                    ) : (
                      columnTasks.map(task => (
                        <TaskCard
                          key={task.id}
                          task={task}
                          onClick={() => openDetail(task)}
                          showMoveButtons={true}
                          onMoveLeft={colIdx > 0 ? () => moveTask(task.id, KANBAN_COLUMNS[colIdx - 1].key) : undefined}
                          onMoveRight={colIdx < KANBAN_COLUMNS.length - 1 ? () => moveTask(task.id, KANBAN_COLUMNS[colIdx + 1].key) : undefined}
                        />
                      ))
                    )}
                  </div>
                </ScrollArea>
              </div>
            );
          })}
        </div>
      ) : mode !== 'task-statistics' && mode !== 'task-timeline' ? (
        /* Table/List view for my-tasks, all-tasks, user-tasks */
        <Card>
          <CardContent className="p-0">
            {filteredComplaints.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                <ListTodo className="w-12 h-12 mx-auto mb-3 opacity-20" />
                <p className="text-sm">No tasks found</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-xs">Ticket#</TableHead>
                      <TableHead className="text-xs">Client</TableHead>
                      <TableHead className="text-xs">Type</TableHead>
                      <TableHead className="text-xs">Priority</TableHead>
                      <TableHead className="text-xs">Status</TableHead>
                      <TableHead className="text-xs hidden md:table-cell">Assigned To</TableHead>
                      <TableHead className="text-xs hidden lg:table-cell">Created</TableHead>
                      <TableHead className="text-xs">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredComplaints.map((c) => (
                      <TableRow key={c.id} className="cursor-pointer hover:bg-accent/30" onClick={() => openDetail(c)}>
                        <TableCell className="text-xs font-mono font-medium">{c.ticketNumber}</TableCell>
                        <TableCell className="text-xs">{c.clientName}</TableCell>
                        <TableCell className="text-xs capitalize">{c.complaintType}</TableCell>
                        <TableCell>
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${priorityColor(c.priority)}`}>
                            {c.priority}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${statusColor(c.status)}`}>
                            {c.status.replace(/_/g, ' ')}
                          </span>
                        </TableCell>
                        <TableCell className="text-xs hidden md:table-cell">
                          {c.assignedEngineer?.name || c.assignedHOD?.name || '-'}
                        </TableCell>
                        <TableCell className="text-xs hidden lg:table-cell">{new Date(c.createdAt).toLocaleDateString()}</TableCell>
                        <TableCell>
                          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={(e) => { e.stopPropagation(); openDetail(c); }}>
                            <Eye className="w-3.5 h-3.5" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      ) : null}

      {/* Task Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="max-w-xl max-h-[80vh] overflow-hidden">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <span className="font-mono">{selectedTask?.ticketNumber}</span>
              {selectedTask && (
                <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${statusColor(selectedTask.status)}`}>
                  {selectedTask.status.replace(/_/g, ' ')}
                </span>
              )}
            </DialogTitle>
            <DialogDescription>Task details and quick actions</DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <ScrollArea className="max-h-[50vh]">
              <div className="space-y-3 pr-3">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><span className="text-muted-foreground">Client:</span> <span className="font-medium">{selectedTask.clientName}</span></div>
                  <div><span className="text-muted-foreground">Phone:</span> <span className="font-medium">{selectedTask.clientPhone}</span></div>
                  <div><span className="text-muted-foreground">Area:</span> <span className="font-medium">{selectedTask.area?.name || '-'}</span></div>
                  <div><span className="text-muted-foreground">Type:</span> <span className="font-medium capitalize">{selectedTask.complaintType}</span></div>
                  <div>
                    <span className="text-muted-foreground">Priority:</span>{' '}
                    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${priorityColor(selectedTask.priority)}`}>
                      {selectedTask.priority}
                    </span>
                  </div>
                  <div><span className="text-muted-foreground">HOD:</span> <span className="font-medium">{selectedTask.assignedHOD?.name || '-'}</span></div>
                  <div><span className="text-muted-foreground">Engineer:</span> <span className="font-medium">{selectedTask.assignedEngineer?.name || '-'}</span></div>
                  <div><span className="text-muted-foreground">Created:</span> <span className="font-medium">{new Date(selectedTask.createdAt).toLocaleString()}</span></div>
                </div>
                <div>
                  <h4 className="text-sm font-semibold mb-1">Description</h4>
                  <p className="text-sm text-muted-foreground bg-muted/50 rounded-lg p-3">{selectedTask.description}</p>
                </div>
                {selectedTask.resolution && (
                  <div>
                    <h4 className="text-sm font-semibold mb-1">Resolution</h4>
                    <p className="text-sm text-muted-foreground bg-emerald-50 dark:bg-emerald-950/20 rounded-lg p-3">{selectedTask.resolution}</p>
                  </div>
                )}
              </div>
            </ScrollArea>
          )}

          {/* Quick Actions */}
          {selectedTask && selectedTask.status !== 'closed' && selectedTask.status !== 'resolved' && (
            <div className="flex flex-wrap gap-2 pt-2 border-t">
              <Button size="sm" onClick={() => setActionDialog('accept')} className="bg-blue-600 hover:bg-blue-700">
                Accept
              </Button>
              <Button size="sm" onClick={() => setActionDialog('update-status')} className="bg-orange-600 hover:bg-orange-700">
                Update Status
              </Button>
              <Button size="sm" onClick={() => setActionDialog('note')} variant="secondary">
                <MessageSquarePlus className="w-3.5 h-3.5 mr-1" /> Add Note
              </Button>
              <Button size="sm" onClick={() => setActionDialog('resolve')} className="bg-emerald-600 hover:bg-emerald-700">
                <CheckCircle2 className="w-3.5 h-3.5 mr-1" /> Resolve
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Action Dialogs */}
      <Dialog open={actionDialog === 'note'} onOpenChange={() => setActionDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Note</DialogTitle>
            <DialogDescription>Add a note to this task</DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <Label>Note</Label>
            <Textarea value={actionNote} onChange={(e) => setActionNote(e.target.value)} placeholder="Enter note..." rows={3} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setActionDialog(null)}>Cancel</Button>
            <Button onClick={handleAction} disabled={actionLoading || !actionNote} className="bg-emerald-600 hover:bg-emerald-700">
              {actionLoading ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : null} Add Note
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={actionDialog === 'resolve'} onOpenChange={() => setActionDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Resolve Task</DialogTitle>
            <DialogDescription>Mark this task as resolved</DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <Label>Resolution</Label>
            <Textarea value={actionResolution} onChange={(e) => setActionResolution(e.target.value)} placeholder="Enter resolution details..." rows={3} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setActionDialog(null)}>Cancel</Button>
            <Button onClick={handleAction} disabled={actionLoading || !actionResolution} className="bg-emerald-600 hover:bg-emerald-700">
              {actionLoading ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <CheckCircle2 className="w-4 h-4 mr-1" />} Resolve
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={actionDialog === 'accept' || actionDialog === 'update-status'} onOpenChange={() => setActionDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{actionDialog === 'accept' ? 'Accept Task' : 'Update Status'}</DialogTitle>
            <DialogDescription>
              {actionDialog === 'accept' ? 'Accept and take ownership of this task' : 'Update the status of this task to In Progress'}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setActionDialog(null)}>Cancel</Button>
            <Button onClick={handleAction} disabled={actionLoading} className="bg-emerald-600 hover:bg-emerald-700">
              {actionLoading ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : null} Confirm
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
