
import React, { useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { toEST } 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 { Textarea } from '@/components/ui/textarea';
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 } 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, "yyyy-MM-dd'T'HH:mm"),
        content: update.content || '',
        collection_ids: update.collection_ids || [],
        violation_ids: update.violation_ids || []
      });
      fetchRelatedItems(update.property_id);
    }
  }, [update, open, reset]);

  const fetchRelatedItems = async (propertyId) => {
    setLoadingRelations(true);
    try {
        const { data: property } = await supabase
            .from('property_owners').select('property_address').eq('id', propertyId).single();

        if (property) {
            const address = property.property_address;
            const { data: violations } = await supabase
                .from('violations').select('id, violation_type, status, created_at, address')
                .eq('address', address).order('created_at', { ascending: false });
            setAvailableViolations(violations || []);

            const { data: collections } = await supabase
                .from('collections').select('id, amount_owed, status, created_at')
                .order('created_at', { ascending: false });
            setAvailableCollections(collections || []);
        }
    } 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);
    }
  };

  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>Property</Label>
                <div className="h-10 px-3 py-2 text-sm border rounded-md bg-muted text-muted-foreground flex items-center">
                    {update?.property?.property_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}>
                      <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">{v.violation_type}</Badge> : null;
                              })
                            : <span className="text-muted-foreground font-normal">No violations linked</span>}
                      </div>
                      <AlertTriangle className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[300px] p-0" align="start">
                    <Command>
                      <CommandInput placeholder="Search violations..." />
                      <CommandEmpty>No violations found.</CommandEmpty>
                      <CommandGroup>
                        {availableViolations.map((violation) => (
                          <CommandItem key={violation.id} value={violation.violation_type + violation.id}
                            onSelect={() => {
                              const current = currentViolationIds;
                              if (current.includes(violation.id)) setValue('violation_ids', current.filter(id => id !== violation.id));
                              else setValue('violation_ids', [...current, violation.id]);
                            }}
                          >
                            <div className={cn("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
                              currentViolationIds.includes(violation.id) ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible"
                            )}><Check className="h-4 w-4" /></div>
                            <div className="flex flex-col">
                              <span className="font-medium">{violation.violation_type}</span>
                              <span className="text-xs text-muted-foreground">{violation.status}</span>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
              </div>

             <div className="space-y-2">
                <Label className="flex items-center gap-2 text-emerald-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}>
                      <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">{c.status || 'Case'}</Badge> : null;
                              })
                            : <span className="text-muted-foreground font-normal">No collections linked</span>}
                      </div>
                      <DollarSign className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-[300px] p-0" align="start">
                    <Command>
                      <CommandInput placeholder="Search collections..." />
                      <CommandEmpty>No collections found.</CommandEmpty>
                      <CommandGroup>
                        {availableCollections.map((collection) => (
                          <CommandItem key={collection.id} value={collection.status + collection.id}
                            onSelect={() => {
                              const current = currentCollectionIds;
                              if (current.includes(collection.id)) setValue('collection_ids', current.filter(id => id !== collection.id));
                              else setValue('collection_ids', [...current, collection.id]);
                            }}
                          >
                            <div className={cn("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
                              currentCollectionIds.includes(collection.id) ? "bg-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible"
                            )}><Check className="h-4 w-4" /></div>
                            <div className="flex flex-col">
                              <span className="font-medium">{collection.status || 'Collection Case'}</span>
                              <span className="text-xs text-muted-foreground">${Number(collection.amount_owed || 0).toFixed(2)}</span>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
              </div>
          </div>

          <div className="space-y-2">
            <Label>Content</Label>
            <Controller name="content" control={control} rules={{ required: true }}
              render={({ field }) => (
                <Textarea value={field.value} onChange={field.onChange} className="min-h-[200px]" placeholder="Update content..." />
              )}
            />
          </div>

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