
import React, { useState, useEffect } from 'react';
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2 } from 'lucide-react';
import { ImageUploadField } from '@/components/ImageUploadField';

function StatusUpdateDialog({ open, onOpenChange, update, onSuccess, currentUserId }) {
  const { toast } = useToast();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [associationId, setAssociationId] = useState('');
  const [requestedAction, setRequestedAction] = useState('');
  const [imageUrls, setImageUrls] = useState([]);
  const [associations, setAssociations] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [createdAt, setCreatedAt] = useState('');

  useEffect(() => {
    if (update) {
      setTitle(update.title);
      setContent(update.content || '');
      setAssociationId(update.association_id);
      setRequestedAction(update.requested_action || '');
      setImageUrls(update.image_urls || []);
      setCreatedAt(update.created_at ? new Date(update.created_at).toISOString().slice(0, 16) : new Date().toISOString().slice(0, 16));
    } else {
      setTitle(''); setContent(''); setAssociationId(''); setRequestedAction(''); setImageUrls([]);
      setCreatedAt(new Date().toISOString().slice(0, 16));
    }
  }, [update, open]);

  useEffect(() => {
    const fetchAssociations = async () => {
      const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
      setAssociations(data || []);
    };
    fetchAssociations();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      if (!title.trim()) throw new Error("Title is required");
      if (!associationId) throw new Error("Association selection is required");

      const updateData = {
        title,
        content,
        association_id: associationId,
        requested_action: requestedAction || null,
        created_by: currentUserId,
        updated_at: new Date().toISOString(),
        image_urls: imageUrls || [],
        created_at: new Date(createdAt).toISOString(),
      };

      let response;
      if (update) {
        response = await supabase.from('status_updates').update(updateData).eq('id', update.id);
      } else {
        response = await supabase.from('status_updates').insert(updateData).select().single();
      }

      if (response.error) throw response.error;

      toast({
        title: `Status Update ${update ? 'Updated' : 'Created'}`,
        description: `The update "${title}" has been saved.`,
      });
      onSuccess();
      onOpenChange(false);

    } catch (error) {
      toast({ variant: 'destructive', title: 'Error', description: error.message });
    } finally {
      setIsSubmitting(false);
    }
  };

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] h-[90vh] sm:h-auto flex flex-col">
        <DialogHeader>
          <DialogTitle>{update ? 'Edit' : 'Add'} Status Update</DialogTitle>
          <DialogDescription>
            {update ? 'Edit the details of the status update.' : 'Create a new status update for an association.'}
          </DialogDescription>
        </DialogHeader>
        
        <ScrollArea className="flex-1 pr-4">
            <form onSubmit={handleSubmit} className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
                <div>
                <label htmlFor="association" className="block text-sm font-medium mb-1">Association *</label>
                <select
                    id="association"
                    value={associationId}
                    onChange={(e) => setAssociationId(e.target.value)}
                    className="w-full p-2 border border-border rounded-md bg-background text-sm"
                    required
                >
                    <option value="" disabled>Select an association</option>
                    {(associations || []).map((a) => (
                    <option key={a.id} value={a.id}>{a.name}</option>
                    ))}
                </select>
                </div>
                <div>
                <label htmlFor="requested_action" className="block text-sm font-medium mb-1">Requested Action</label>
                <select
                    id="requested_action"
                    value={requestedAction}
                    onChange={(e) => setRequestedAction(e.target.value)}
                    className="w-full p-2 border border-border rounded-md bg-background text-sm"
                >
                    <option value="">None</option>
                    <option value="approve">Request Approval</option>
                    <option value="reject">Request Denial</option>
                </select>
                </div>
            </div>

            <div>
                <label htmlFor="created_at" className="block text-sm font-medium mb-1">Date & Time</label>
                <input
                  id="created_at"
                  type="datetime-local"
                  value={createdAt}
                  onChange={(e) => setCreatedAt(e.target.value)}
                  className="w-full p-2 border border-border rounded-md bg-background text-sm"
                />
            </div>
            
            <div>
                <label htmlFor="title" className="block text-sm font-medium mb-1">Title *</label>
                <input
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full p-2 border border-border rounded-md bg-background"
                required
                />
            </div>

            <div>
                <label htmlFor="content" className="block text-sm font-medium mb-1">Content</label>
                <div className="h-64 mb-2">
                    <ReactQuill 
                        theme="snow" 
                        value={content} 
                        onChange={setContent} 
                        modules={modules}
                        className="bg-background h-52"
                    />
                </div>
            </div>
            
            <div className="pt-8">
              <label className="block text-sm font-medium mb-2">Images</label>
              <ImageUploadField 
                images={imageUrls || []} 
                onChange={setImageUrls}
                disabled={isSubmitting}
                bucket="status-update-images"
              />
            </div>

            </form>
        </ScrollArea>

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

export default StatusUpdateDialog;
