import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Plus, X, Tag } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

const COLORS = [
  { name: 'Blue', value: 'blue' },
  { name: 'Red', value: 'red' },
  { name: 'Green', value: 'green' },
  { name: 'Amber', value: 'amber' },
  { name: 'Purple', value: 'purple' },
  { name: 'Slate', value: 'slate' },
];

export function OwnerUpdateTagManager({ associationId, open, onOpenChange }) {
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(true);
  const [newTagName, setNewTagName] = useState('');
  const [newTagColor, setNewTagColor] = useState('blue');
  const [submitting, setSubmitting] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (open && associationId) fetchTags();
  }, [open, associationId]);

  const fetchTags = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase.from('owner_update_tags').select('*').eq('association_id', associationId).order('name');
      if (error) throw error;
      setTags(data || []);
    } catch (error) {
      toast({ variant: "destructive", title: "Error", description: "Failed to load tags." });
    } finally {
      setLoading(false);
    }
  };

  const handleAddTag = async (e) => {
    e.preventDefault();
    if (!newTagName.trim()) return;
    setSubmitting(true);
    try {
      const { data, error } = await supabase.from('owner_update_tags').insert({ name: newTagName.trim(), color: newTagColor, association_id: associationId }).select().single();
      if (error) throw error;
      setTags([...tags, data]);
      setNewTagName('');
      setNewTagColor('blue');
      toast({ title: "Tag created" });
    } catch (error) {
      toast({ variant: "destructive", title: "Error", description: "Failed to create tag." });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteTag = async (tagId) => {
    try {
      const { error } = await supabase.from('owner_update_tags').delete().eq('id', tagId);
      if (error) throw error;
      setTags(tags.filter(t => t.id !== tagId));
      toast({ title: "Tag deleted" });
    } catch (error) {
      toast({ variant: "destructive", title: "Error", description: "Failed to delete tag." });
    }
  };

  const getColorClass = (color) => {
    switch (color) {
      case 'red': return 'bg-red-100 text-red-700 border-red-200';
      case 'green': return 'bg-green-100 text-green-700 border-green-200';
      case 'amber': return 'bg-amber-100 text-amber-700 border-amber-200';
      case 'purple': return 'bg-purple-100 text-purple-700 border-purple-200';
      case 'slate': return 'bg-slate-100 text-slate-700 border-slate-200';
      default: return 'bg-blue-100 text-blue-700 border-blue-200';
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader><DialogTitle>Manage Tags</DialogTitle></DialogHeader>
        <form onSubmit={handleAddTag} className="flex items-end gap-2 mb-4">
          <div className="flex-1 space-y-2">
            <Label>New Tag Name</Label>
            <Input value={newTagName} onChange={(e) => setNewTagName(e.target.value)} placeholder="e.g. Urgent, Maintenance" />
          </div>
          <div className="w-[100px] space-y-2">
            <Label>Color</Label>
            <Select value={newTagColor} onValueChange={setNewTagColor}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>{COLORS.map(c => <SelectItem key={c.value} value={c.value}>{c.name}</SelectItem>)}</SelectContent>
            </Select>
          </div>
          <Button type="submit" size="icon" disabled={submitting || !newTagName.trim()}>
            {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
          </Button>
        </form>
        <div className="space-y-2 max-h-[300px] overflow-y-auto pr-2">
          {loading ? (
            <div className="flex justify-center py-4"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
          ) : tags.length === 0 ? (
            <p className="text-center text-sm text-muted-foreground py-4">No tags created yet.</p>
          ) : (
            <div className="grid grid-cols-1 gap-2">
              {tags.map(tag => (
                <div key={tag.id} className="flex items-center justify-between p-2 rounded-md border bg-muted/30">
                  <Badge variant="outline" className={getColorClass(tag.color)}><Tag className="w-3 h-3 mr-1" />{tag.name}</Badge>
                  <Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground hover:text-destructive" onClick={() => handleDeleteTag(tag.id)}>
                    <X className="w-3 h-3" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
