
import React, { useState, useEffect, useMemo } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Send, Eye, RefreshCw, Paperclip } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useAuth } from '@/contexts/AuthContext';

export default function NotifyBoardSendDialog({ 
  open, 
  onOpenChange, 
  clients = [], 
  additionalEmails = [], 
  loadingClients = false,
  refreshClients = () => {} 
}) {
  const { user } = useAuth();
  const { toast } = useToast();
  
  const [templates, setTemplates] = useState([]);
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [selectedSenderId, setSelectedSenderId] = useState('');
  const [senders, setSenders] = useState([]);
  
  const [subject, setSubject] = useState('');
  const [body, setBody] = useState('');
  const [variableValues, setVariableValues] = useState({});
  const [selectedRecipients, setSelectedRecipients] = useState([]); 
  
  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [sending, setSending] = useState(false);
  const [sendResults, setSendResults] = useState(null);
  const [oneOffAttachments, setOneOffAttachments] = useState([]);

  useEffect(() => {
    if (open) {
       if (refreshClients) refreshClients();
    } else {
       resetState();
    }
  }, [open]);

  useEffect(() => {
    if (senders.length > 0 && !selectedSenderId) {
      const def = senders.find(s => s.is_default);
      if (def) setSelectedSenderId(def.id);
      else setSelectedSenderId(senders[0].id);
    }
  }, [senders, selectedSenderId]);

  const resetState = () => {
      setSelectedTemplateId('');
      setSubject('');
      setBody('');
      setVariableValues({});
      setSelectedRecipients([]);
      setSendResults(null);
      setOneOffAttachments([]);
  };

  useEffect(() => {
    if (selectedTemplateId === 'custom') {
        setSubject('');
        setBody('');
        setVariableValues({});
    } else if (selectedTemplateId) {
        const tmpl = templates.find(t => t.id === selectedTemplateId);
        if (tmpl) {
            setSubject(tmpl.subject);
            setBody(tmpl.body);
            setVariableValues({});
        }
    }
  }, [selectedTemplateId, templates]);

  const selectedTemplateAttachments = useMemo(() => {
      const tmpl = templates.find(t => t.id === selectedTemplateId);
      return tmpl?.attachments || [];
  }, [selectedTemplateId, templates]);

  const allAttachments = useMemo(() => {
      return [...selectedTemplateAttachments, ...oneOffAttachments];
  }, [selectedTemplateAttachments, oneOffAttachments]);

  const handleSend = async () => {
     if (!subject || !body) {
        toast({ variant: "destructive", title: "Validation Error", description: "Subject and Body are required." });
        return;
     }
     if (selectedRecipients.length === 0) {
        toast({ variant: "destructive", title: "Selection Error", description: "Please select at least one recipient." });
        return;
     }
     if (!selectedSenderId) {
        toast({ variant: "destructive", title: "Sender Error", description: "Please select a valid sender." });
        return;
     }

     setSending(true);
     setSendResults(null);
     
     const results = [];
     
     try {
         for (const recipient of selectedRecipients) {
             const { email, clientId } = recipient;
             const clientInfo = clients.find(c => c.id === clientId) || { name: 'Homeowner Association' };
             
             const context = { clientName: clientInfo.name, ...variableValues };
             const finalSubject = subject; // Placeholder for template variable replacement

             // TODO: Integrate email sending service
             console.log(`Would send email to ${email}: ${finalSubject}`);
             results.push({ email, status: 'sent', error: null });
         }

         setSendResults(results);
         
         const successfulCount = results.filter(r => r.status === 'sent').length;
         if (successfulCount > 0) {
             toast({ title: 'Success', description: `Successfully delivered ${successfulCount} emails.` });
         }
         
         const failedCount = results.filter(r => r.status === 'failed').length;
         if (failedCount > 0) {
             toast({ variant: 'destructive', title: 'Partial Delivery', description: `${failedCount} emails failed to send.` });
         }

     } catch (err) {
        console.error("Critical Send Error:", err);
        toast({ variant: "destructive", title: "Sending Failed", description: err.message });
     } finally {
        setSending(false);
     }
  };

  const isLoading = loadingClients || loadingTemplates;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
       <DialogContent className="max-w-6xl h-[90vh] flex flex-col p-0 gap-0">
          <DialogHeader className="p-6 pb-2 border-b shrink-0">
             <div className="flex justify-between items-center pr-8">
                <div>
                   <DialogTitle>Send Board Notification</DialogTitle>
                   <DialogDescription>Select recipients and customize your message.</DialogDescription>
                </div>
                {loadingClients && (
                   <span className="text-xs text-primary bg-primary/10 px-2 py-1 rounded-full flex items-center gap-1 animate-pulse">
                      <RefreshCw className="w-3 h-3 animate-spin" /> Updating emails...
                   </span>
                )}
             </div>
          </DialogHeader>

          {sendResults ? (
              <div className="flex-1 overflow-y-auto p-6">
                 <div className="space-y-3">
                   <h3 className="font-semibold text-lg">Delivery Results</h3>
                   {sendResults.map((r, i) => (
                     <div key={i} className={`flex items-center justify-between p-3 rounded-md border ${r.status === 'sent' ? 'bg-emerald-50 border-emerald-200' : 'bg-destructive/10 border-destructive/20'}`}>
                       <span className="text-sm font-medium">{r.email}</span>
                       <span className={`text-xs font-semibold uppercase ${r.status === 'sent' ? 'text-emerald-600' : 'text-destructive'}`}>{r.status}</span>
                     </div>
                   ))}
                 </div>
              </div>
          ) : (
              <div className="flex-1 overflow-hidden grid grid-cols-1 lg:grid-cols-2">
                 <div className="flex flex-col border-r h-full overflow-hidden bg-background">
                     {isLoading && !clients.length ? (
                         <div className="flex-1 flex flex-col items-center justify-center space-y-4">
                             <Loader2 className="w-8 h-8 animate-spin text-primary" />
                             <p className="text-muted-foreground">Loading data...</p>
                         </div>
                     ) : (
                         <ScrollArea className="flex-1 p-6">
                             <div className="space-y-6">
                                 <div className="space-y-2">
                                     <Label>Sender</Label>
                                     <Select value={selectedSenderId} onValueChange={setSelectedSenderId}>
                                        <SelectTrigger><SelectValue placeholder="Select Sender" /></SelectTrigger>
                                        <SelectContent>
                                            {senders.map(s => (
                                                <SelectItem key={s.id} value={s.id}>{s.label} ({s.email_address})</SelectItem>
                                            ))}
                                        </SelectContent>
                                     </Select>
                                 </div>
                                 <div className="space-y-2">
                                    <Label>Template</Label>
                                    <Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
                                       <SelectTrigger><SelectValue placeholder="Choose email template..." /></SelectTrigger>
                                       <SelectContent>
                                          <SelectItem value="custom">Use Custom Message</SelectItem>
                                          {templates.map(t => <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>)}
                                       </SelectContent>
                                    </Select>
                                 </div>
                                 <div className="space-y-3 border p-4 rounded-lg bg-muted/50">
                                     <div className="space-y-2">
                                         <Label className="text-xs">Subject</Label>
                                         <Input value={subject} onChange={e => setSubject(e.target.value)} placeholder="Email Subject" />
                                     </div>
                                     <div className="space-y-2">
                                         <Label className="text-xs">Body</Label>
                                         <Textarea 
                                             value={body}
                                             onChange={e => setBody(e.target.value)}
                                             className="min-h-[150px]"
                                             placeholder="Email body content..."
                                         />
                                     </div>
                                 </div>
                                 {selectedTemplateAttachments.length > 0 && (
                                     <div className="space-y-2 border p-4 rounded-lg bg-muted/50">
                                         <Label className="font-semibold">Template Attachments</Label>
                                         {selectedTemplateAttachments.map((file, idx) => (
                                             <div key={idx} className="flex items-center gap-2 text-xs bg-background p-2 rounded border text-muted-foreground">
                                                 <Paperclip className="w-3 h-3" /><span className="truncate flex-1">{file.name}</span>
                                             </div>
                                         ))}
                                     </div>
                                 )}
                             </div>
                         </ScrollArea>
                     )}
                 </div>
                 <div className="bg-muted/30 flex flex-col h-full overflow-hidden border-l">
                    <div className="p-4 border-b bg-background flex items-center justify-between shrink-0">
                        <div className="flex items-center gap-2 font-medium text-foreground"><Eye className="w-4 h-4" /> Live Preview</div>
                    </div>
                    <div className="flex-1 w-full h-full relative bg-muted">
                         <div className="absolute inset-0 overflow-auto p-6">
                            <div className="bg-background rounded-lg border p-6 shadow-sm">
                              <h3 className="font-semibold mb-2">{subject || 'No subject'}</h3>
                              <div className="text-sm text-muted-foreground whitespace-pre-wrap">{body || 'No body content'}</div>
                            </div>
                         </div>
                    </div>
                 </div>
              </div>
          )}

          <DialogFooter className="p-4 border-t bg-background shrink-0">
             {sendResults ? (
                 <div className="flex gap-2 w-full justify-end">
                    <Button variant="outline" onClick={() => setSendResults(null)}><RefreshCw className="w-4 h-4 mr-2" /> Start New</Button>
                    <Button onClick={() => onOpenChange(false)}>Close</Button>
                 </div>
             ) : (
                 <>
                     <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
                     <Button onClick={handleSend} disabled={sending || isLoading || !selectedSenderId || selectedRecipients.length === 0} className="min-w-[160px]">
                         {sending ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Send className="w-4 h-4 mr-2" />}
                         {sending ? 'Sending...' : `Send to ${selectedRecipients.length} Recipients`}
                     </Button>
                 </>
             )}
          </DialogFooter>
       </DialogContent>
    </Dialog>
  );
}
