import React, { useState } from 'react';
import { formatShortDateEST } from '@/lib/timezoneUtils';
import { Edit2, Trash2, Calendar, User, Building2, Loader2, Repeat, MessageSquare, Home } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useCommentCount } from '@/hooks/useCommentCount';

export default function TaskCard({ task, canManage, onEdit, onRefresh }) {
  const { toast } = useToast();
  const [updatingStatus, setUpdatingStatus] = useState(false);
  const { count: commentCount, loading: countLoading } = useCommentCount(task?.id, 'task');

  const handleDelete = async () => {
    const { error } = await supabase.from('tasks').delete().eq('id', task.id);
    if (error) {
      toast({ variant: "destructive", title: "Error deleting task", description: error.message });
    } else {
      toast({ title: "Task Deleted", description: "The task has been successfully deleted." });
      if (onRefresh) onRefresh();
    }
  };

  const handleStatusToggle = async (checked) => {
    if (updatingStatus) return;
    setUpdatingStatus(true);
    const newStatus = checked ? 'completed' : 'pending';
    try {
      const updates = { status: newStatus };
      if (checked) updates.completed_at = new Date().toISOString();
      else updates.completed_at = null;

      const { error } = await supabase.from('tasks').update(updates).eq('id', task.id);
      if (error) throw error;

      let description = `Task marked as ${newStatus}.`;
      if (task.recurring && newStatus === 'completed') {
        description = "Task completed. A new recurring instance has been created.";
      }
      toast({ title: "Status Updated", description });
      if (onRefresh) onRefresh();
    } catch (error) {
      toast({ variant: "destructive", title: "Error updating status", description: error.message });
    } finally {
      setUpdatingStatus(false);
    }
  };

  const getPriorityColor = (priority) => {
    switch (priority) {
      case 'high': return 'bg-destructive/10 text-destructive border-destructive/20';
      case 'medium': return 'bg-amber-100 text-amber-700 border-amber-200';
      case 'low': return 'bg-muted text-muted-foreground border-border';
      default: return 'bg-muted text-muted-foreground border-border';
    }
  };

  return (
    <div className="group flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-card border-b border-border hover:bg-muted/50 transition-colors duration-200 gap-4">
      <div className="flex items-start gap-4 flex-1 min-w-0">
        <div className="mt-1 shrink-0 relative flex items-center justify-center w-5 h-5">
          {updatingStatus ? (
            <Loader2 className="w-4 h-4 animate-spin text-primary" />
          ) : (
            <Checkbox
              id={`task-${task.id}`}
              checked={task.status === 'completed'}
              onCheckedChange={handleStatusToggle}
              className="data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
            />
          )}
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2 mb-1 flex-wrap">
            <label
              htmlFor={`task-${task.id}`}
              className={cn(
                "font-semibold text-foreground truncate cursor-pointer hover:underline decoration-muted-foreground/50",
                task.status === 'completed' && "text-muted-foreground line-through"
              )}
            >
              {task.title}
            </label>
            <Badge variant="outline" className={cn("capitalize text-xs font-medium", getPriorityColor(task.priority))}>
              {task.priority}
            </Badge>
            {task.recurring && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Badge variant="secondary" className="px-1.5 h-5 cursor-help">
                      <Repeat className="w-3 h-3" />
                    </Badge>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Recurring: {task.recurring_interval || 'weekly'}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            )}
            {task.is_workflow_task && (
              <Badge variant="secondary" className="px-1.5 h-5 text-[10px]">
                Workflow
              </Badge>
            )}
            {!countLoading && commentCount > 0 && (
              <Badge variant="secondary" className="px-1.5 h-5 gap-1 flex items-center">
                <MessageSquare className="w-3 h-3" />
                <span className="text-[10px]">({commentCount})</span>
              </Badge>
            )}
          </div>
          <p className={cn("text-sm text-muted-foreground truncate pr-4", task.status === 'completed' && "text-muted-foreground/60")}>
            {task.description || 'No description provided'}
          </p>
        </div>
      </div>

      <div className="flex flex-wrap sm:flex-nowrap items-center gap-4 sm:gap-6 text-sm text-muted-foreground shrink-0">
        {task.associations && (
          <div className="flex items-center gap-2 min-w-[100px]">
            <Building2 className="w-4 h-4 text-muted-foreground/60" />
            <span className="truncate max-w-[120px]">{task.associations.name}</span>
          </div>
        )}
        <div className="flex items-center gap-2 min-w-[120px]">
          <User className="w-4 h-4 text-muted-foreground/60" />
          <span className="truncate max-w-[140px]">{task.assigned_user_name || 'Unassigned'}</span>
        </div>
        <div className="flex items-center gap-2 min-w-[100px]">
          <Calendar className="w-4 h-4 text-muted-foreground/60" />
          <span>{task.due_date ? formatShortDateEST(task.due_date) : 'No due date'}</span>
        </div>
      </div>

      {canManage && (
        <div className="flex items-center gap-2 shrink-0 opacity-100 sm:opacity-0 group-hover:opacity-100 transition-opacity">
          <Button variant="ghost" size="icon" onClick={onEdit} className="h-8 w-8 text-muted-foreground hover:text-primary hover:bg-primary/10">
            <Edit2 className="w-4 h-4" />
          </Button>
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10">
                <Trash2 className="w-4 h-4" />
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Delete Task</AlertDialogTitle>
                <AlertDialogDescription>Are you sure? This action cannot be undone.</AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90">Delete</AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      )}
    </div>
  );
}
