
import React, { useState, useEffect } from 'react';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useNotifyOwners } from '@/contexts/NotifyOwnersContext';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Loader2, CheckCircle2, Copy, ExternalLink, Eye, X, Paperclip, Upload, Users } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { Badge } from '@/components/ui/badge';
import { useFileUpload } from '@/hooks/useFileUpload';

// Success Dialog Component
const SuccessDialog = ({ open, onOpenChange, result }) => {
  const { toast } = useToast();
  if (!result) return null;

  const copyLink = () => {
    if (result.proofUrl) {
      navigator.clipboard.writeText(result.proofUrl);
      toast({ title: 'Copied', description: 'Proof URL copied to clipboard.' });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Notifications Sent</DialogTitle>
          <DialogDescription>Your email blast has been delivered successfully.</DialogDescription>
        </DialogHeader>
        <div className="flex flex-col items-center justify-center py-6 text-center space-y-4">
          <div className="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mb-2">
            <CheckCircle2 className="w-10 h-10 text-emerald-600" />
          </div>
          <h2 className="text-2xl font-bold">Notifications Sent!</h2>
          <p className="text-muted-foreground max-w-sm">
            Successfully delivered to <strong>{result.count}</strong> owners. 
            {result.failed > 0 && <span className="text-amber-600 ml-1">({result.failed} failed)</span>}
          </p>
          
          <div className="w-full bg-muted p-4 rounded-lg border mt-4 space-y-3">
             <div className="flex items-center justify-between text-sm">
                <span className="font-medium">Validation ID:</span>
                <span className="font-mono text-muted-foreground">{result.validationId}</span>
             </div>
             
             {result.proofUrl && (
               <div className="pt-3 border-t flex flex-col gap-2">
                  <span className="text-xs font-medium text-muted-foreground uppercase">Proof Document</span>
                  <div className="flex gap-2">
                     <Button variant="outline" className="flex-1 text-xs" onClick={() => window.open(result.proofUrl, '_blank')}>
                       <ExternalLink className="w-4 h-4 mr-2" /> View PDF
                     </Button>
                     <Button variant="outline" className="flex-1 text-xs" onClick={copyLink}>
                       <Copy className="w-4 h-4 mr-2" /> Copy Link
                     </Button>
                  </div>
               </div>
             )}
          </div>
        </div>
        <DialogFooter className="sm:justify-center">
          <Button onClick={() => onOpenChange(false)}>Close</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

// Reusable Email Chip Input
const EmailChipInput = ({ emails, setEmails, placeholder, label, helpText }) => {
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  const processInput = (value) => {
    const splitEmails = value.split(',').map((e) => e.trim()).filter(Boolean);
    const newValidEmails = [];
    let hasError = false;

    splitEmails.forEach((email) => {
      if (validateEmail(email)) {
        if (!emails.includes(email)) newValidEmails.push(email);
      } else {
        hasError = true;
      }
    });

    if (newValidEmails.length > 0) setEmails([...emails, ...newValidEmails]);
    if (hasError) setError('One or more email addresses are invalid.');
    else { setError(''); setInputValue(''); }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      if (inputValue.trim()) processInput(inputValue);
    }
  };

  const handleBlur = () => { if (inputValue.trim()) processInput(inputValue); };
  const removeEmail = (emailToRemove) => { setEmails(emails.filter((email) => email !== emailToRemove)); setError(''); };

  return (
    <div className="space-y-2">
      <div className="flex items-baseline justify-between">
        <Label>{label}</Label>
        {helpText && <span className="text-xs text-muted-foreground">{helpText}</span>}
      </div>
      <div className={`flex flex-wrap gap-2 p-2 border rounded-md bg-background min-h-[40px] items-center focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 ${error ? 'border-destructive ring-destructive' : 'border-input'}`}>
        {emails.map((email) => (
          <Badge key={email} variant="secondary" className="flex items-center gap-1 py-1 px-2 text-sm">
            {email}
            <button type="button" className="ml-1 text-muted-foreground hover:text-foreground focus:outline-none" onClick={() => removeEmail(email)}>
              <X className="w-3 h-3" />
            </button>
          </Badge>
        ))}
        <input
          type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={handleKeyDown} onBlur={handleBlur}
          placeholder={emails.length === 0 ? placeholder : ''}
          className="flex-1 outline-none bg-transparent min-w-[200px] text-sm text-foreground placeholder:text-muted-foreground"
        />
      </div>
      {error && <p className="text-xs text-destructive">{error}</p>}
    </div>
  );
};


export default function NotifyOwnersDialog({ open, onOpenChange, initialTemplate, selectedOwners = [] }) {
  const { user } = useAuth();
  const { sendNotification, templates, clients, selectedClientId, setSelectedClientId, owners, getOwnersByConsent } = useNotifyOwners();
  const { toast } = useToast();
  const { uploadFiles, uploading } = useFileUpload();

  const [senders, setSenders] = useState([]);
  const [senderId, setSenderId] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState('custom');
  const [subject, setSubject] = useState('');
  const [body, setBody] = useState('');
  const [ccEmails, setCcEmails] = useState([]);
  const [bccEmails, setBccEmails] = useState([]);
  const [attachments, setAttachments] = useState([]);
  const [sending, setSending] = useState(false);
  const [targetGroup, setTargetGroup] = useState('all'); 
  const [showPreview, setShowPreview] = useState(false);

  const [successResult, setSuccessResult] = useState(null);
  const [showSuccess, setShowSuccess] = useState(false);

  // Compute owner stats based on context owners
  const allOwnersWithEmail = getOwnersByConsent ? getOwnersByConsent(false) : [];
  const consentedOwners = getOwnersByConsent ? getOwnersByConsent(true) : [];
  const selectedOwnersWithEmail = selectedOwners.filter(owner => owner.email);
  const recipientCount = targetGroup === 'selected' ? selectedOwnersWithEmail.length : targetGroup === 'consented' ? consentedOwners.length : allOwnersWithEmail.length;

  useEffect(() => {
    if (open && user) {
      fetchSenders();
      setCcEmails([]); setBccEmails([]);
      setSelectedTemplate('custom'); setAttachments([]);
      setSuccessResult(null); setShowPreview(false);
      setTargetGroup(selectedOwnersWithEmail.length > 0 ? 'selected' : 'all');

      // Pre-fill from template if provided
      if (initialTemplate) {
        setSubject(initialTemplate.subject || '');
        setBody(initialTemplate.body_html || initialTemplate.body || '');
        setSelectedTemplate(initialTemplate.id || 'custom');
      } else {
        setSubject('');
        setBody('');
      }
    }
  }, [open, user, initialTemplate]);

  const fetchSenders = async () => {
    const { data: result, error } = await supabase.functions.invoke('send-smtp-email', {
      body: { action: 'list_senders' }
    });

    if (error || !result?.success) {
      console.error('Failed to load email senders:', error || result?.error);
      setSenders([]);
      setSenderId('');
      return;
    }

    const availableSenders = result.senders || [];
    if (availableSenders.length > 0) {
      setSenders(availableSenders);
      setSenderId(availableSenders[0].id);
    } else {
      setSenders([]);
      setSenderId('');
    }
  };

  const handleTemplateChange = (val) => {
    setSelectedTemplate(val);
    if (val !== 'custom') {
      const tmpl = templates.find(t => t.id === val);
      if (tmpl) { 
        setSubject(tmpl.subject || ''); 
        setBody(tmpl.body_html || tmpl.body || ''); 
      }
    } else { setSubject(''); setBody(''); }
  };

  const handleFileSelect = async (e) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;
    
    const uploaded = await uploadFiles(files, 'files', 'email-attachments');
    if (uploaded.length > 0) {
      setAttachments(prev => [...prev, ...uploaded]);
      toast({ title: 'Files attached', description: `${uploaded.length} file(s) added.` });
    }
    e.target.value = '';
  };

  const removeAttachment = (index) => {
    setAttachments(prev => prev.filter((_, i) => i !== index));
  };

  const getPreviewHtml = () => {
      const clientInfo = clients.find(c => c.id === selectedClientId) || { name: 'Association' };
      const formattedBody = body.replace(/\n/g, '<br/>');
      return `<p><strong>To:</strong> ${clientInfo.name} Owners (${recipientCount} recipients)</p><hr/><p>${formattedBody}</p>`;
  };

  const handleSend = async () => {
    if (!subject || subject.trim() === '' || !body || body.trim() === '' || !senderId) {
      toast({ variant: 'destructive', title: 'Validation Error', description: 'Subject, body, and sender are required.' });
      return;
    }

    if (!selectedClientId) {
      toast({ variant: 'destructive', title: 'No Association', description: 'Please select an association first.' });
      return;
    }

    if (senders.length === 0) {
      toast({ variant: 'destructive', title: 'No Sender', description: 'Please configure an email sender in Email Settings first.' });
      return;
    }

    if (recipientCount === 0) {
      toast({ variant: 'destructive', title: 'No Recipients', description: `No owners with email found in the "${targetGroup}" group for this association.` });
      return;
    }

    setSending(true);
    const selectedSender = senders.find(s => s.id === senderId);

    const result = await sendNotification({
        subject, body, senderId,
        senderName: selectedSender?.sender_name,
        senderEmail: selectedSender?.email_address,
        cc: ccEmails, bcc: bccEmails, attachments, targetGroup, customOwners: selectedOwnersWithEmail
    });

    setSending(false);

    if (result.success) {
       setSuccessResult(result);
       onOpenChange(false);
       setShowSuccess(true);
       toast({ title: 'Success', description: 'Notifications successfully sent.' });
    } else {
       toast({ variant: 'destructive', title: 'Sending Failed', description: result.error || 'An unexpected error occurred.' });
    }
  };

  const selectedAssocName = clients.find(c => c.id === selectedClientId)?.name || 'No association';

  return (
    <>
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Notify Owners</DialogTitle>
          <DialogDescription>Send an email blast to property owners. A cryptographic proof PDF will be generated.</DialogDescription>
        </DialogHeader>

        {showPreview ? (
             <div className="space-y-4 py-4">
                 <div className="flex items-center justify-between mb-2">
                     <h3 className="font-semibold">Email Preview</h3>
                     <Button variant="outline" size="sm" onClick={() => setShowPreview(false)}>Back to Editor</Button>
                 </div>
                 <div className="bg-muted border rounded-md p-4 space-y-3">
                     <div>
                         <span className="text-xs font-semibold text-muted-foreground uppercase">Association:</span>
                         <p className="font-medium">{selectedAssocName}</p>
                     </div>
                     <div>
                         <span className="text-xs font-semibold text-muted-foreground uppercase">Subject:</span>
                         <p className="font-medium">{subject}</p>
                     </div>
                     {(ccEmails.length > 0 || bccEmails.length > 0) && (
                       <div className="flex flex-col gap-1 border-t border-b py-2">
                         {ccEmails.length > 0 && <div className="text-sm"><span className="text-xs font-semibold text-muted-foreground uppercase mr-2">CC:</span>{ccEmails.join(', ')}</div>}
                         {bccEmails.length > 0 && <div className="text-sm"><span className="text-xs font-semibold text-muted-foreground uppercase mr-2">BCC:</span>{bccEmails.join(', ')}</div>}
                       </div>
                     )}
                     <div>
                         <span className="text-xs font-semibold text-muted-foreground uppercase">Body:</span>
                         <div className="mt-2 bg-background p-4 border rounded shadow-sm prose max-w-none" dangerouslySetInnerHTML={{ __html: getPreviewHtml() }} />
                     </div>
                     {attachments.length > 0 && (
                       <div>
                         <span className="text-xs font-semibold text-muted-foreground uppercase">Attachments:</span>
                         <div className="flex flex-wrap gap-2 mt-2">
                           {attachments.map((att, i) => (
                             <Badge key={i} variant="secondary" className="text-xs">{att.name}</Badge>
                           ))}
                         </div>
                       </div>
                     )}
                 </div>
             </div>
        ) : (
             <div className="space-y-5 py-4">
                 {/* Association Selector + Owner Stats */}
                 <div className="grid grid-cols-2 gap-4">
                   <div className="space-y-2">
                     <Label>Association</Label>
                     <Select value={selectedClientId || ''} onValueChange={setSelectedClientId}>
                       <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
                       <SelectContent>
                         {clients.map(c => (
                           <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                         ))}
                       </SelectContent>
                     </Select>
                   </div>
                   <div className="space-y-2">
                     <Label>Recipients</Label>
                     <div className="flex items-center gap-3 h-10 px-3 border rounded-md bg-muted/50">
                       <Users className="w-4 h-4 text-muted-foreground" />
                       <div className="flex gap-3 text-sm">
                          <span><strong>{allOwnersWithEmail.length}</strong> <span className="text-muted-foreground">w/ email</span></span>
                         <span className="text-border">|</span>
                         <span><strong>{consentedOwners.length}</strong> <span className="text-muted-foreground">consented</span></span>
                          {selectedOwnersWithEmail.length > 0 && <><span className="text-border">|</span><span><strong>{selectedOwnersWithEmail.length}</strong> <span className="text-muted-foreground">selected</span></span></>}
                       </div>
                     </div>
                   </div>
                 </div>

                 <div className="grid grid-cols-2 gap-4">
                   <div className="space-y-2">
                       <Label>From Sender</Label>
                       <Select value={senderId} onValueChange={setSenderId}>
                           <SelectTrigger><SelectValue placeholder="Select Sender" /></SelectTrigger>
                           <SelectContent>
                               {senders.map(s => (
                                   <SelectItem key={s.id} value={s.id}>{s.sender_name} ({s.email_address})</SelectItem>
                               ))}
                           </SelectContent>
                       </Select>
                       {senders.length === 0 && (
                         <p className="text-xs text-destructive">No verified senders found. Configure one in Email Settings.</p>
                       )}
                   </div>
       
                   <div className="space-y-2">
                       <Label>Target Group</Label>
                       <Select value={targetGroup} onValueChange={setTargetGroup}>
                           <SelectTrigger><SelectValue /></SelectTrigger>
                           <SelectContent>
                                {selectedOwnersWithEmail.length > 0 && <SelectItem value="selected">Selected Homeowners ({selectedOwnersWithEmail.length})</SelectItem>}
                                <SelectItem value="all">All Owners w/ Email ({allOwnersWithEmail.length})</SelectItem>
                               <SelectItem value="consented">Consented Only ({consentedOwners.length})</SelectItem>
                           </SelectContent>
                       </Select>
                   </div>
                 </div>

                 <EmailChipInput label="CC (Carbon Copy)" emails={ccEmails} setEmails={setCcEmails} placeholder="email1@example.com, email2@example.com" helpText="Press Enter or comma to add" />
                 <EmailChipInput label="BCC (Blind Carbon Copy)" emails={bccEmails} setEmails={setBccEmails} placeholder="email1@example.com, email2@example.com" helpText="Recipients won't see these" />
       
                 <div className="space-y-2">
                    <Label>Apply Template (Optional)</Label>
                    <Select value={selectedTemplate} onValueChange={handleTemplateChange}>
                        <SelectTrigger><SelectValue placeholder="Write your own message" /></SelectTrigger>
                        <SelectContent>
                            <SelectItem value="custom">-- No Template --</SelectItem>
                            {templates.map(t => <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>)}
                        </SelectContent>
                    </Select>
                  </div>
       
                 <div className="space-y-2">
                   <Label>Subject</Label>
                   <Input placeholder="Notice of Upcoming Meeting..." value={subject} onChange={e => setSubject(e.target.value)} />
                 </div>
       
                 <div className="space-y-2">
                   <div className="flex justify-between">
                      <Label>Message Body</Label>
                      <span className="text-xs text-muted-foreground">Variables: {'{{ownerName}}, {{propertyAddress}}, {{clientName}}, {{date}}'}</span>
                   </div>
                   <Textarea placeholder="Dear {{ownerName}}..." className="min-h-[150px]" value={body} onChange={e => setBody(e.target.value)} />
                 </div>

                 {/* Attachments */}
                 <div className="space-y-2">
                   <div className="flex items-center justify-between">
                     <Label className="flex items-center gap-2">
                       <Paperclip className="w-4 h-4" /> Attachments
                     </Label>
                     <label className="cursor-pointer">
                       <input type="file" multiple className="hidden" onChange={handleFileSelect} />
                       <Button variant="outline" size="sm" asChild disabled={uploading}>
                         <span>
                           {uploading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Upload className="w-4 h-4 mr-2" />}
                           {uploading ? 'Uploading...' : 'Add Files'}
                         </span>
                       </Button>
                     </label>
                   </div>
                   {attachments.length > 0 && (
                     <div className="flex flex-wrap gap-2">
                       {attachments.map((att, i) => (
                         <Badge key={i} variant="secondary" className="flex items-center gap-1 py-1 px-2 text-sm">
                           <Paperclip className="w-3 h-3" />
                           {att.name}
                           <span className="text-xs text-muted-foreground ml-1">
                             ({(att.size / 1024).toFixed(0)}KB)
                           </span>
                           <button type="button" className="ml-1 text-muted-foreground hover:text-foreground" onClick={() => removeAttachment(i)}>
                             <X className="w-3 h-3" />
                           </button>
                         </Badge>
                       ))}
                     </div>
                   )}
                   <p className="text-xs text-muted-foreground">Max 25MB per file. Supported: PDF, DOCX, images, etc.</p>
                 </div>
             </div>
        )}

        <DialogFooter className="flex justify-between items-center sm:justify-between">
          <Button variant="ghost" onClick={() => setShowPreview(!showPreview)} className="text-primary hover:text-primary/80">
             <Eye className="w-4 h-4 mr-2" />
             {showPreview ? 'Edit Message' : 'Preview Output'}
          </Button>
          <div className="flex gap-2">
              <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
              <Button onClick={handleSend} disabled={sending || !subject || !body || !senderId || !selectedClientId}>
                {sending ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
                {sending ? 'Sending & Validating...' : `Send to ${recipientCount} Owner${recipientCount !== 1 ? 's' : ''}`}
              </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <SuccessDialog open={showSuccess} onOpenChange={setShowSuccess} result={successResult} />
    </>
  );
}
