import React, { useState } from 'react';
import { X, Trash2, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';

export default function BulkTaskActionBar({ selectedIds, onClear, onSuccess, users = [] }) {
  const [loading, setLoading] = useState(false);
  const count = selectedIds.length;

  const applyUpdate = async (updates) => {
    setLoading(true);
    try {
      const { error } = await supabase.from('tasks').update(updates).in('id', selectedIds);
      if (error) throw error;
      toast.success(`${count} task(s) updated`);
      onClear();
      onSuccess();
    } catch (err) {
      toast.error('Update failed', { description: err.message });
    } finally {
      setLoading(false);
    }
  };

  const handleBulkDelete = async () => {
    setLoading(true);
    try {
      const { error } = await supabase.from('tasks').delete().in('id', selectedIds);
      if (error) throw error;
      toast.success(`${count} task(s) deleted`);
      onClear();
      onSuccess();
    } catch (err) {
      toast.error('Delete failed', { description: err.message });
    } finally {
      setLoading(false);
    }
  };

  if (count === 0) return null;

  return (
    <div className="sticky top-0 z-20 bg-primary text-primary-foreground rounded-lg px-4 py-3 flex flex-wrap items-center gap-3 shadow-lg animate-in slide-in-from-top-2">
      <span className="text-sm font-semibold whitespace-nowrap">{count} selected</span>

      <Select onValueChange={(v) => applyUpdate({ status: v })} disabled={loading}>
        <SelectTrigger className="w-[140px] h-8 bg-primary-foreground/15 border-primary-foreground/20 text-primary-foreground text-xs">
          <SelectValue placeholder="Set Status" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="pending">Pending</SelectItem>
          <SelectItem value="in_progress">In Progress</SelectItem>
          <SelectItem value="completed">Completed</SelectItem>
        </SelectContent>
      </Select>

      <Select onValueChange={(v) => applyUpdate({ priority: v })} disabled={loading}>
        <SelectTrigger className="w-[140px] h-8 bg-primary-foreground/15 border-primary-foreground/20 text-primary-foreground text-xs">
          <SelectValue placeholder="Set Priority" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="low">Low</SelectItem>
          <SelectItem value="medium">Medium</SelectItem>
          <SelectItem value="high">High</SelectItem>
          <SelectItem value="urgent">Urgent</SelectItem>
        </SelectContent>
      </Select>

      <Select onValueChange={(v) => applyUpdate({ assigned_to: v === 'unassigned' ? null : v })} disabled={loading}>
        <SelectTrigger className="w-[160px] h-8 bg-primary-foreground/15 border-primary-foreground/20 text-primary-foreground text-xs">
          <SelectValue placeholder="Assign To" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="unassigned">Unassigned</SelectItem>
          {users.map((u) => (
            <SelectItem key={u.id} value={u.id}>{u.name}</SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Input
        type="date"
        className="w-[150px] h-8 bg-primary-foreground/15 border-primary-foreground/20 text-primary-foreground text-xs"
        onChange={(e) => {
          if (e.target.value) applyUpdate({ due_date: e.target.value });
        }}
        disabled={loading}
      />

      <AlertDialog>
        <AlertDialogTrigger asChild>
          <Button variant="ghost" size="sm" className="h-8 text-primary-foreground hover:bg-destructive hover:text-destructive-foreground gap-1" disabled={loading}>
            <Trash2 className="w-3.5 h-3.5" /> Delete
          </Button>
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete {count} Task(s)</AlertDialogTitle>
            <AlertDialogDescription>This will permanently delete the selected tasks. This cannot be undone.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleBulkDelete} className="bg-destructive hover:bg-destructive/90">Delete All</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {loading && <Loader2 className="w-4 h-4 animate-spin" />}

      <Button variant="ghost" size="icon" className="h-7 w-7 ml-auto text-primary-foreground hover:bg-primary-foreground/20" onClick={onClear}>
        <X className="w-4 h-4" />
      </Button>
    </div>
  );
}
