import React, { useState, useEffect } from 'react';
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';
import { useForm, Controller } from 'react-hook-form';
import { toEST, formatShortDateEST } from '@/lib/timezoneUtils';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Loader2, AlertTriangle, DollarSign, Check, X } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';

export function OwnerUpdateDialog({ update, open, onOpenChange, onSuccess }) {
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [availableViolations, setAvailableViolations] = useState([]);
  const [availableCollections, setAvailableCollections] = useState([]);
  const [loadingRelations, setLoadingRelations] = useState(false);

  const { control, handleSubmit, reset, setValue, watch } = useForm({
    defaultValues: {
      posted_at: toEST(new Date(), "yyyy-MM-dd'T'HH:mm"),
      content: '',
      collection_ids: [],
      violation_ids: []
    }
  });

  const currentCollectionIds = watch('collection_ids');
  const currentViolationIds = watch('violation_ids');

  useEffect(() => {
    if (update && open) {
      reset({
        posted_at: toEST(update.posted_at || update.created_at, "yyyy-MM-dd'T'HH:mm"),
        content: update.content || '',
        collection_ids: update.collection_ids || [],
        violation_ids: update.violation_ids || []
      });
      if (update.unit_id) fetchRelatedItems(update.unit_id);
    }
  }, [update, open, reset]);

  const fetchRelatedItems = async (unitId) => {
    setLoadingRelations(true);
    try {
      const { data: unit } = await supabase.from('units').select('address, association_id').eq('id', unitId).single();
      if (unit) {
        const [vRes, cRes] = await Promise.all([
          supabase.from('violations').select('id, violation_type, status, created_at').eq('association_id', unit.association_id).eq('unit_id', unitId).order('created_at', { ascending: false }),
          supabase.from('collections').select('id, amount_owed, status, created_at').eq('association_id', unit.association_id).order('created_at', { ascending: false })
        ]);
        setAvailableViolations(vRes.data || []);
        setAvailableCollections(cRes.data || []);
      }
    } catch (error) {
      console.error("Error fetching related items:", error);
    } finally {
      setLoadingRelations(false);
    }
  };

  const onSubmit = async (data) => {
    if (!update) return;
    setIsSubmitting(true);
    try {
      const { error } = await supabase.from('owner_updates').update({
        content: data.content,
        posted_at: new Date(data.posted_at).toISOString(),
        collection_ids: data.collection_ids,
        violation_ids: data.violation_ids
      }).eq('id', update.id);
      if (error) throw error;
      toast({ title: "Updated", description: "Update modified successfully." });
      onSuccess();
      onOpenChange(false);
    } catch (err) {
      console.error(err);
      toast({ variant: "destructive", title: "Error", description: "Failed to update record." });
    } finally {
      setIsSubmitting(false);
    }
  };

  const toggleViolation = (id) => {
    const current = currentViolationIds || [];
    setValue('violation_ids', current.includes(id) ? current.filter(i => i !== id) : [...current, id]);
  };

  const toggleCollection = (id) => {
    const current = currentCollectionIds || [];
    setValue('collection_ids', current.includes(id) ? current.filter(i => i !== id) : [...current, id]);
  };

  const modules = { toolbar: [[{ 'header': [1, 2, false] }], ['bold', 'italic', 'underline', 'strike', 'blockquote'], [{ 'list': 'ordered' }, { 'list': 'bullet' }], ['clean']] };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px]">
        <DialogHeader><DialogTitle>Edit Update</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Date & Time</Label>
              <Controller name="posted_at" control={control} rules={{ required: true }} render={({ field }) => <Input type="datetime-local" {...field} />} />
            </div>
            <div className="space-y-2">
              <Label>Unit</Label>
              <div className="h-10 px-3 py-2 text-sm border rounded-md bg-muted/30 text-muted-foreground flex items-center">
                {update?.units?.unit_number || update?.units?.address || 'Unknown'}
              </div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label className="flex items-center gap-2 text-amber-600"><AlertTriangle className="w-4 h-4" /> Linked Violations</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" role="combobox" className="w-full justify-between h-auto min-h-[40px]" disabled={loadingRelations} type="button">
                    <div className="flex flex-wrap gap-1">
                      {currentViolationIds.length > 0 ? currentViolationIds.map(id => {
                        const v = availableViolations.find(v => v.id === id);
                        return v ? <Badge key={id} variant="secondary" className="text-xs bg-amber-100 text-amber-800 border-amber-200">{v.violation_type}</Badge> : null;
                      }) : <span className="text-muted-foreground">Select violations...</span>}
                    </div>
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[300px] p-0" align="start">
                  <Command><CommandInput placeholder="Search..." /><CommandList><CommandEmpty>No violations found.</CommandEmpty>
                    <CommandGroup>{availableViolations.map(v => {
                      const isSelected = currentViolationIds.includes(v.id);
                      return (
                        <CommandItem key={v.id} value={v.violation_type + " " + v.id} onSelect={() => toggleViolation(v.id)} className="cursor-pointer">
                          <div className={cn("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary", isSelected ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible")}><Check className="h-4 w-4" /></div>
                          <div className="flex flex-col flex-1 min-w-0">
                            <span className="font-medium truncate">{v.violation_type}</span>
                            <span className="text-xs text-muted-foreground">{v.status} • {formatShortDateEST(v.created_at)}</span>
                          </div>
                        </CommandItem>
                      );
                    })}</CommandGroup>
                  </CommandList></Command>
                </PopoverContent>
              </Popover>
            </div>

            <div className="space-y-2">
              <Label className="flex items-center gap-2 text-green-600"><DollarSign className="w-4 h-4" /> Linked Collections</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" role="combobox" className="w-full justify-between h-auto min-h-[40px]" disabled={loadingRelations} type="button">
                    <div className="flex flex-wrap gap-1">
                      {currentCollectionIds.length > 0 ? currentCollectionIds.map(id => {
                        const c = availableCollections.find(c => c.id === id);
                        return c ? <Badge key={id} variant="secondary" className="text-xs bg-green-100 text-green-800 border-green-200">${Number(c.amount_owed).toFixed(2)}</Badge> : null;
                      }) : <span className="text-muted-foreground">Select collections...</span>}
                    </div>
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[300px] p-0" align="start">
                  <Command><CommandInput placeholder="Search..." /><CommandList><CommandEmpty>No collections found.</CommandEmpty>
                    <CommandGroup>{availableCollections.map(c => {
                      const isSelected = currentCollectionIds.includes(c.id);
                      return (
                        <CommandItem key={c.id} value={c.id} onSelect={() => toggleCollection(c.id)} className="cursor-pointer">
                          <div className={cn("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary", isSelected ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible")}><Check className="h-4 w-4" /></div>
                          <div className="flex flex-col flex-1 min-w-0">
                            <span className="font-medium truncate">Collection</span>
                            <span className="text-xs text-muted-foreground">${Number(c.amount_owed).toFixed(2)} • {c.status}</span>
                          </div>
                        </CommandItem>
                      );
                    })}</CommandGroup>
                  </CommandList></Command>
                </PopoverContent>
              </Popover>
            </div>
          </div>

          <div className="space-y-2">
            <Label>Content</Label>
            <Controller name="content" control={control} rules={{ required: true }} render={({ field }) => (
              <div className="h-64 mb-12"><ReactQuill theme="snow" value={field.value} onChange={field.onChange} modules={modules} className="bg-background h-52" /></div>
            )} />
          </div>

          <DialogFooter>
            <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={isSubmitting}>{isSubmitting ? <><Loader2 className="w-4 h-4 animate-spin mr-2" />Saving...</> : "Save Changes"}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
