import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Tag, Search, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { format } from 'date-fns';
import { cn } from '@/lib/utils';

export function BulkOwnerUpdateTagDialog({ open, onOpenChange, clientId, onSuccess }) {
  const [updates, setUpdates] = useState([]);
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedUpdates, setSelectedUpdates] = useState([]);
  const [loading, setLoading] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [tagsToAdd, setTagsToAdd] = useState([]);
  const [tagsToRemove, setTagsToRemove] = useState([]);
  const { toast } = useToast();

  useEffect(() => {
    if (open && clientId) {
      loadData();
      setSelectedUpdates([]);
      setTagsToAdd([]);
      setTagsToRemove([]);
      setSearchQuery('');
    }
  }, [open, clientId]);

  const loadData = async () => {
    setLoading(true);
    try {
      const { data: tagsData, error: tagsError } = await supabase
        .from('owner_update_tags')
        .select('*')
        .eq('client_id', clientId)
        .order('name');
      if (tagsError) throw tagsError;
      setAvailableTags(tagsData || []);

      // Fetch recent updates
      setUpdates([]);
    } catch (error) {
      console.error('Error loading data:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to load data.' });
    } finally {
      setLoading(false);
    }
  };

  const handleSelectAll = () => {
    if (selectedUpdates.length === filteredUpdates.length) {
      setSelectedUpdates([]);
    } else {
      setSelectedUpdates(filteredUpdates.map(u => u.id));
    }
  };

  const handleSelectUpdate = (id) => {
    setSelectedUpdates(prev => prev.includes(id) ? prev.filter(uid => uid !== id) : [...prev, id]);
  };

  const toggleTagToAdd = (tag) => {
    if (tagsToRemove.find(t => t.id === tag.id)) setTagsToRemove(prev => prev.filter(t => t.id !== tag.id));
    if (tagsToAdd.find(t => t.id === tag.id)) setTagsToAdd(prev => prev.filter(t => t.id !== tag.id));
    else setTagsToAdd(prev => [...prev, tag]);
  };

  const toggleTagToRemove = (tag) => {
    if (tagsToAdd.find(t => t.id === tag.id)) setTagsToAdd(prev => prev.filter(t => t.id !== tag.id));
    if (tagsToRemove.find(t => t.id === tag.id)) setTagsToRemove(prev => prev.filter(t => t.id !== tag.id));
    else setTagsToRemove(prev => [...prev, tag]);
  };

  const handleSubmit = async () => {
    if (selectedUpdates.length === 0) return;
    if (tagsToAdd.length === 0 && tagsToRemove.length === 0) { onOpenChange(false); return; }

    setProcessing(true);
    try {
      const updatesToProcess = updates.filter(u => selectedUpdates.includes(u.id));
      const promises = updatesToProcess.map(async (update) => {
        let currentTags = Array.isArray(update.tags) ? [...update.tags] : [];
        if (tagsToRemove.length > 0) {
          const removeIds = tagsToRemove.map(t => t.id);
          currentTags = currentTags.filter(t => !removeIds.includes(t.id));
        }
        if (tagsToAdd.length > 0) {
          tagsToAdd.forEach(tag => {
            if (!currentTags.some(t => t.id === tag.id)) currentTags.push(tag);
          });
        }
        return supabase.from('owner_updates').update({ tags: currentTags }).eq('id', update.id);
      });
      await Promise.all(promises);
      toast({ title: "Bulk Update Complete", description: `Updated tags for ${selectedUpdates.length} items.` });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error("Bulk update error:", error);
      toast({ variant: "destructive", title: "Error", description: "Failed to process bulk updates." });
    } finally {
      setProcessing(false);
    }
  };

  const filteredUpdates = updates.filter(u =>
    u.content?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl h-[85vh] flex flex-col p-0 gap-0 overflow-hidden">
        <DialogHeader className="p-6 pb-2 shrink-0">
          <DialogTitle>Bulk Tag Editor</DialogTitle>
          <DialogDescription>Select updates to apply or remove tags in bulk.</DialogDescription>
        </DialogHeader>

        <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
            <div className="grid grid-cols-2 gap-4 p-4 mx-6 mt-2 mb-4 bg-muted/50 border rounded-lg shrink-0">
                <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase text-green-600">Add Tags</Label>
                    <div className="flex flex-wrap gap-2 max-h-24 overflow-y-auto pr-1">
                        {availableTags.map(tag => (
                            <Badge key={tag.id} variant={tagsToAdd.some(t => t.id === tag.id) ? "default" : "outline"}
                                className={cn("cursor-pointer transition-all", tagsToAdd.some(t => t.id === tag.id) ? "bg-green-600 hover:bg-green-700 border-green-600 text-white" : "hover:bg-green-50")}
                                onClick={() => toggleTagToAdd(tag)}>
                                {tagsToAdd.some(t => t.id === tag.id) && <Tag className="w-3 h-3 mr-1" />}{tag.name}
                            </Badge>
                        ))}
                        {availableTags.length === 0 && <span className="text-xs text-muted-foreground">No tags available.</span>}
                    </div>
                </div>
                <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase text-red-600">Remove Tags</Label>
                    <div className="flex flex-wrap gap-2 max-h-24 overflow-y-auto pr-1">
                        {availableTags.map(tag => (
                            <Badge key={tag.id} variant={tagsToRemove.some(t => t.id === tag.id) ? "default" : "outline"}
                                className={cn("cursor-pointer transition-all", tagsToRemove.some(t => t.id === tag.id) ? "bg-red-600 hover:bg-red-700 border-red-600 text-white" : "hover:bg-red-50")}
                                onClick={() => toggleTagToRemove(tag)}>
                                {tagsToRemove.some(t => t.id === tag.id) && <X className="w-3 h-3 mr-1" />}{tag.name}
                            </Badge>
                        ))}
                        {availableTags.length === 0 && <span className="text-xs text-muted-foreground">No tags available.</span>}
                    </div>
                </div>
            </div>

            <div className="flex flex-col flex-1 min-h-0 mx-6 mb-4 border rounded-md overflow-hidden">
                <div className="flex items-center gap-2 p-2 border-b shrink-0">
                     <div className="relative flex-1">
                        <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                        <Input placeholder="Search updates..." className="pl-9 h-9" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
                     </div>
                     <div className="text-xs text-muted-foreground font-medium px-2">{selectedUpdates.length} selected</div>
                </div>

                <div className="bg-muted/50 p-2 border-b flex items-center gap-3 text-xs font-semibold text-muted-foreground shrink-0">
                    <Checkbox checked={filteredUpdates.length > 0 && selectedUpdates.length === filteredUpdates.length} onCheckedChange={handleSelectAll} />
                    <span>Select All Visible</span>
                </div>
                
                <ScrollArea className="flex-1 w-full">
                    {loading ? (
                        <div className="flex justify-center p-8"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
                    ) : (
                        <div className="divide-y">
                            {filteredUpdates.length === 0 ? (
                                <div className="p-8 text-center text-muted-foreground text-sm">No updates found.</div>
                            ) : (
                                filteredUpdates.map(update => (
                                    <div key={update.id} className={cn("flex items-start gap-3 p-3 hover:bg-muted/50 transition-colors cursor-pointer", selectedUpdates.includes(update.id) && "bg-primary/5")} onClick={() => handleSelectUpdate(update.id)}>
                                        <Checkbox checked={selectedUpdates.includes(update.id)} onCheckedChange={() => handleSelectUpdate(update.id)} className="mt-1" />
                                        <div className="flex-1 min-w-0 space-y-1">
                                            <div className="text-xs text-muted-foreground line-clamp-2" dangerouslySetInnerHTML={{ __html: update.content }} />
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    )}
                </ScrollArea>
            </div>
        </div>

        <DialogFooter className="p-4 border-t shrink-0">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={processing || selectedUpdates.length === 0}>
             {processing ? (<><Loader2 className="w-4 h-4 mr-2 animate-spin" />Updating...</>) : `Update ${selectedUpdates.length} Items`}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
