import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, Mail, AlertTriangle, CheckCircle2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useAuth } from '@/contexts/AuthContext';

export default function HomeownerRequestNotifyDialog({ open, onOpenChange, requestId, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [request, setRequest] = useState(null);
  const [previewTab, setPreviewTab] = useState('recipients');
  
  const [sendResults, setSendResults] = useState(null); 

  useEffect(() => {
    if (open && requestId) {
      loadData();
    } else {
      resetState();
    }
  }, [open, requestId]);

  const resetState = () => {
      setRequest(null);
      setSendResults(null);
  };

  const loadData = async () => {
    setLoading(true);
    try {
        const { data: reqData, error: reqError } = await supabase
            .from('homeowner_requests')
            .select('*')
            .eq('id', requestId)
            .single();
        
        if (reqError) throw reqError;
        setRequest(reqData);
    } catch (error) {
        console.error("Error loading notify dialog data:", error);
        toast({ variant: 'destructive', title: 'Data access error', description: 'Failed to retrieve homeowner request.' });
    } finally {
        setLoading(false);
    }
  };

  const handleSend = async () => {
    setSending(true);
    setSendResults(null);

    try {
        // Placeholder: In production, this would call an edge function or email service
        toast({ title: 'Notification', description: 'Email notification feature requires email service configuration.' });
        setSendResults({ success: true });
        if (onSuccess) onSuccess();
    } catch (error) {
        console.error("Send failed:", error);
        toast({ variant: 'destructive', title: 'Failed to send', description: error.message });
        setSendResults({ success: false, error: error.message });
    } finally {
        setSending(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px] h-[85vh] flex flex-col p-0 gap-0">
        <DialogHeader className="p-6 pb-2 border-b shrink-0">
          <DialogTitle>Notify Homeowners</DialogTitle>
          <DialogDescription>Send email notification for "{request?.title}"</DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-hidden flex flex-col min-h-0">
            {sendResults ? (
                <div className="flex-1 p-6 overflow-y-auto">
                    <div className="text-center mb-6">
                        {sendResults.success ? (
                             <div className="inline-flex items-center justify-center p-3 bg-emerald-100 rounded-full mb-3">
                                 <CheckCircle2 className="w-8 h-8 text-emerald-600" />
                             </div>
                        ) : (
                             <div className="inline-flex items-center justify-center p-3 bg-destructive/10 rounded-full mb-3">
                                 <AlertTriangle className="w-8 h-8 text-destructive" />
                             </div>
                        )}
                        <h3 className="text-lg font-semibold">
                             {sendResults.success ? 'Notifications Sent' : 'Sending Failed'}
                        </h3>
                    </div>
                </div>
            ) : (
                <div className="flex-1 p-6">
                    {loading ? (
                        <div className="flex flex-col items-center justify-center py-12 gap-4">
                            <Loader2 className="animate-spin text-muted-foreground w-8 h-8" />
                            <p className="text-muted-foreground text-sm">Loading request details...</p>
                        </div>
                    ) : (
                        <div className="text-center text-muted-foreground py-12">
                            <Mail className="w-12 h-12 mx-auto mb-4 opacity-50" />
                            <p>Email notification functionality requires email service configuration.</p>
                        </div>
                    )}
                </div>
            )}
        </div>

        <DialogFooter className="p-4 border-t shrink-0">
          {sendResults ? (
              <Button onClick={() => onOpenChange(false)}>Close</Button>
          ) : (
              <>
                <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
                <Button 
                    onClick={handleSend} 
                    disabled={sending || loading}
                >
                    {sending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Mail className="mr-2 h-4 w-4" />}
                    {sending ? 'Sending...' : 'Send Notifications'}
                </Button>
              </>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
