import { useState } from 'react';
import { Bell, CheckCircle2, Clock, AlertTriangle, Home, Calendar } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useTasks } from '@/hooks/useTasks';
import { useTenancyAlerts } from '@/hooks/useTenancyAlerts';
import { formatDistanceToNow, isPast, isToday, addDays, format } from 'date-fns';
import { useNavigate } from 'react-router-dom';
import { cn } from '@/lib/utils';

export function TaskNotificationDropdown() {
  const { tasks, toggleComplete } = useTasks();
  const { data: tenancyAlerts = [] } = useTenancyAlerts();
  const navigate = useNavigate();
  const [isOpen, setIsOpen] = useState(false);
  const [activeTab, setActiveTab] = useState('tasks');

  // Filter tasks for notifications
  const pendingTasks = tasks.filter((task) => task.status !== 'completed');
  
  const overdueTasks = pendingTasks.filter(
    (task) => task.due_date && isPast(new Date(task.due_date)) && !isToday(new Date(task.due_date))
  );
  
  const todayTasks = pendingTasks.filter(
    (task) => task.due_date && isToday(new Date(task.due_date))
  );
  
  const upcomingTasks = pendingTasks.filter(
    (task) => task.due_date && 
    !isPast(new Date(task.due_date)) && 
    !isToday(new Date(task.due_date)) &&
    new Date(task.due_date) <= addDays(new Date(), 7)
  );

  // Filter tenancy alerts
  const inspectionAlerts = tenancyAlerts.filter(a => a.type === 'inspection');
  const renewalAlerts = tenancyAlerts.filter(a => a.type === 'renewal');
  const overdueAlerts = tenancyAlerts.filter(a => a.daysUntilDue < 0);
  const urgentAlerts = tenancyAlerts.filter(a => a.daysUntilDue >= 0 && a.daysUntilDue <= 7);

  const taskNotifications = overdueTasks.length + todayTasks.length + upcomingTasks.length;
  const tenancyNotifications = tenancyAlerts.length;
  const totalNotifications = taskNotifications + tenancyNotifications;

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high':
        return 'text-destructive';
      case 'medium':
        return 'text-warning';
      default:
        return 'text-muted-foreground';
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'call':
        return '📞';
      case 'email':
        return '✉️';
      case 'meeting':
        return '📅';
      case 'follow-up':
        return '🔄';
      default:
        return '📝';
    }
  };

  const handleTaskClick = (taskContactId: string | null) => {
    setIsOpen(false);
    if (taskContactId) {
      navigate(`/contacts/${taskContactId}`);
    } else {
      navigate('/tasks');
    }
  };

  const handleTenancyAlertClick = (tenancyId: string) => {
    setIsOpen(false);
    navigate(`/tenancies/${tenancyId}`);
  };

  const renderTaskItem = (task: typeof tasks[0], showOverdue = false) => (
    <DropdownMenuItem
      key={task.id}
      className="flex flex-col items-start gap-1 p-3 cursor-pointer"
      onClick={() => handleTaskClick(task.contact_id)}
    >
      <div className="flex w-full items-center justify-between gap-2">
        <div className="flex items-center gap-2 min-w-0 flex-1">
          <span className="shrink-0">{getTypeIcon(task.type)}</span>
          <span className="font-medium truncate">{task.title}</span>
        </div>
        <Badge 
          variant={task.priority === 'high' ? 'destructive' : 'secondary'} 
          className="shrink-0 text-xs"
        >
          {task.priority}
        </Badge>
      </div>
      {task.due_date && (
        <div className={cn(
          "text-xs flex items-center gap-1",
          showOverdue ? "text-destructive" : "text-muted-foreground"
        )}>
          {showOverdue ? (
            <AlertTriangle className="h-3 w-3" />
          ) : (
            <Clock className="h-3 w-3" />
          )}
          {showOverdue ? 'Overdue: ' : 'Due: '}
          {formatDistanceToNow(new Date(task.due_date), { addSuffix: true })}
        </div>
      )}
    </DropdownMenuItem>
  );

  const renderTenancyAlertItem = (alert: typeof tenancyAlerts[0]) => {
    const isOverdue = alert.daysUntilDue < 0;
    const isUrgent = alert.daysUntilDue >= 0 && alert.daysUntilDue <= 7;

    return (
      <DropdownMenuItem
        key={alert.id}
        className="flex flex-col items-start gap-1 p-3 cursor-pointer"
        onClick={() => handleTenancyAlertClick(alert.tenancyId)}
      >
        <div className="flex w-full items-center justify-between gap-2">
          <div className="flex items-center gap-2 min-w-0 flex-1">
            {alert.type === 'inspection' ? (
              <Home className="h-4 w-4 shrink-0 text-blue-500" />
            ) : (
              <Calendar className="h-4 w-4 shrink-0 text-amber-500" />
            )}
            <span className="font-medium truncate">
              {alert.type === 'inspection' ? 'Inspection Due' : 'Renewal Due'}
            </span>
          </div>
          <Badge 
            variant={isOverdue ? 'destructive' : isUrgent ? 'default' : 'secondary'} 
            className="shrink-0 text-xs"
          >
            {alert.type}
          </Badge>
        </div>
        <p className="text-xs text-muted-foreground truncate w-full">
          {alert.tenancyReference} - {alert.propertyAddress}
        </p>
        <div className={cn(
          "text-xs flex items-center gap-1",
          isOverdue ? "text-destructive" : isUrgent ? "text-warning" : "text-muted-foreground"
        )}>
          {isOverdue ? (
            <AlertTriangle className="h-3 w-3" />
          ) : (
            <Clock className="h-3 w-3" />
          )}
          {isOverdue 
            ? `Overdue by ${Math.abs(alert.daysUntilDue)} days` 
            : `Due ${format(alert.dueDate, 'dd MMM yyyy')} (${alert.daysUntilDue} days)`
          }
        </div>
      </DropdownMenuItem>
    );
  };

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" className="relative">
          <Bell className="h-4 w-4" />
          {totalNotifications > 0 && (
            <span className={cn(
              "absolute -right-0.5 -top-0.5 flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-bold text-primary-foreground",
              (overdueTasks.length > 0 || overdueAlerts.length > 0) ? "bg-destructive" : "bg-primary"
            )}>
              {totalNotifications > 9 ? '9+' : totalNotifications}
            </span>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-96">
        <DropdownMenuLabel className="flex items-center justify-between">
          <span>Notifications</span>
          {totalNotifications > 0 && (
            <Badge variant="secondary" className="text-xs">
              {totalNotifications} total
            </Badge>
          )}
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="w-full grid grid-cols-2">
            <TabsTrigger value="tasks" className="text-xs">
              Tasks {taskNotifications > 0 && `(${taskNotifications})`}
            </TabsTrigger>
            <TabsTrigger value="tenancies" className="text-xs">
              Tenancies {tenancyNotifications > 0 && `(${tenancyNotifications})`}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="tasks" className="mt-0">
            <ScrollArea className="h-[350px]">
              {taskNotifications === 0 ? (
                <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                  <CheckCircle2 className="h-8 w-8 mb-2" />
                  <p className="text-sm">All caught up!</p>
                  <p className="text-xs">No pending task reminders</p>
                </div>
              ) : (
                <>
                  {overdueTasks.length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-destructive flex items-center gap-1 py-2">
                        <AlertTriangle className="h-3 w-3" />
                        Overdue ({overdueTasks.length})
                      </DropdownMenuLabel>
                      {overdueTasks.slice(0, 5).map((task) => renderTaskItem(task, true))}
                      <DropdownMenuSeparator />
                    </>
                  )}
                  
                  {todayTasks.length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-warning flex items-center gap-1 py-2">
                        <Clock className="h-3 w-3" />
                        Due Today ({todayTasks.length})
                      </DropdownMenuLabel>
                      {todayTasks.slice(0, 5).map((task) => renderTaskItem(task))}
                      <DropdownMenuSeparator />
                    </>
                  )}
                  
                  {upcomingTasks.length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-muted-foreground flex items-center gap-1 py-2">
                        <Clock className="h-3 w-3" />
                        Upcoming This Week ({upcomingTasks.length})
                      </DropdownMenuLabel>
                      {upcomingTasks.slice(0, 5).map((task) => renderTaskItem(task))}
                    </>
                  )}
                </>
              )}
            </ScrollArea>
          </TabsContent>

          <TabsContent value="tenancies" className="mt-0">
            <ScrollArea className="h-[350px]">
              {tenancyNotifications === 0 ? (
                <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                  <CheckCircle2 className="h-8 w-8 mb-2" />
                  <p className="text-sm">No alerts!</p>
                  <p className="text-xs">All inspections and renewals are up to date</p>
                </div>
              ) : (
                <>
                  {overdueAlerts.length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-destructive flex items-center gap-1 py-2">
                        <AlertTriangle className="h-3 w-3" />
                        Overdue ({overdueAlerts.length})
                      </DropdownMenuLabel>
                      {overdueAlerts.slice(0, 5).map(renderTenancyAlertItem)}
                      <DropdownMenuSeparator />
                    </>
                  )}

                  {urgentAlerts.length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-warning flex items-center gap-1 py-2">
                        <Clock className="h-3 w-3" />
                        Due This Week ({urgentAlerts.length})
                      </DropdownMenuLabel>
                      {urgentAlerts.slice(0, 5).map(renderTenancyAlertItem)}
                      <DropdownMenuSeparator />
                    </>
                  )}

                  {inspectionAlerts.filter(a => a.daysUntilDue > 7).length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-blue-500 flex items-center gap-1 py-2">
                        <Home className="h-3 w-3" />
                        Inspections ({inspectionAlerts.filter(a => a.daysUntilDue > 7).length})
                      </DropdownMenuLabel>
                      {inspectionAlerts.filter(a => a.daysUntilDue > 7).slice(0, 5).map(renderTenancyAlertItem)}
                      <DropdownMenuSeparator />
                    </>
                  )}

                  {renewalAlerts.filter(a => a.daysUntilDue > 7).length > 0 && (
                    <>
                      <DropdownMenuLabel className="text-xs text-amber-500 flex items-center gap-1 py-2">
                        <Calendar className="h-3 w-3" />
                        Renewals ({renewalAlerts.filter(a => a.daysUntilDue > 7).length})
                      </DropdownMenuLabel>
                      {renewalAlerts.filter(a => a.daysUntilDue > 7).slice(0, 5).map(renderTenancyAlertItem)}
                    </>
                  )}
                </>
              )}
            </ScrollArea>
          </TabsContent>
        </Tabs>
        
        <DropdownMenuSeparator />
        <DropdownMenuItem 
          className="justify-center text-primary cursor-pointer"
          onClick={() => {
            setIsOpen(false);
            navigate(activeTab === 'tasks' ? '/tasks' : '/tenancies');
          }}
        >
          View All {activeTab === 'tasks' ? 'Tasks' : 'Tenancies'}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}