
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Loader2, Plus } from 'lucide-react';

const AVAILABLE_VARIABLES = [
  { key: 'client_name', desc: 'Association Name' },
  { key: 'recipient_name', desc: 'Board Member Name' },
  { key: 'alert_type', desc: 'Type of Alert' },
  { key: 'date', desc: 'Relevant Date' },
  { key: 'amount', desc: 'Monetary Amount' },
  { key: 'address', desc: 'Property Address' },
  { key: 'status', desc: 'Current Status' }
];

const DUMMY_VARIABLES = {
  client_name: 'Sample Association',
  recipient_name: 'John Doe',
  alert_type: 'Urgent Maintenance',
  date: new Date().toLocaleDateString(),
  amount: '$1,250.00',
  address: '123 Maple Avenue',
  status: 'Pending'
};

export default function NotifyBoardTemplateDialog({ open, onOpenChange, template, onSave }) {
  const [activeTab, setActiveTab] = useState('edit');
  const [formData, setFormData] = useState({
    name: '',
    subject: '',
    body: '',
    variables: [],
    attachments: []
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (template) {
      setFormData({
        name: template.name || '',
        subject: template.subject || '',
        body: template.body || '',
        variables: template.variables || [],
        attachments: template.attachments || []
      });
    } else {
      setFormData({
        name: '',
        subject: '',
        body: 'Please log in to your account to review the requested vote for documentation.',
        variables: [],
        attachments: []
      });
    }
    setActiveTab('edit');
  }, [template, open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.name || !formData.subject || !formData.body) return;
    
    setIsSubmitting(true);
    await onSave(formData);
    setIsSubmitting(false);
    onOpenChange(false);
  };

  const insertVariable = (variableKey) => {
    const variableTag = `{{${variableKey}}}`;
    setFormData(prev => ({
        ...prev,
        body: prev.body + ` ${variableTag} `
    }));
  };

  const getPreviewHtml = () => {
    let preview = formData.body || '';
    Object.entries(DUMMY_VARIABLES).forEach(([key, val]) => {
      preview = preview.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), val);
    });
    return preview;
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[90vh] flex flex-col p-0 gap-0">
        <DialogHeader className="p-6 pb-2 border-b shrink-0">
          <DialogTitle>{template ? 'Edit Template' : 'Create New Template'}</DialogTitle>
          <DialogDescription>
             Design email templates for board notifications. The header and footer will be automatically applied.
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-hidden flex flex-col min-h-0 bg-muted/30">
          <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col min-h-0">
            <div className="px-6 py-2 border-b bg-background shrink-0">
              <TabsList className="grid w-[300px] grid-cols-2">
                <TabsTrigger value="edit">Editor</TabsTrigger>
                <TabsTrigger value="preview">Preview</TabsTrigger>
              </TabsList>
            </div>

            <TabsContent value="edit" className="flex-1 p-0 m-0 overflow-hidden flex flex-col min-h-0">
               <div className="flex-1 overflow-y-auto pr-2 grid grid-cols-1 lg:grid-cols-3 gap-6 p-6">
                 <div className="lg:col-span-2 space-y-4">
                    <div className="space-y-2">
                       <Label>Template Name</Label>
                       <Input 
                         value={formData.name} 
                         onChange={(e) => setFormData({...formData, name: e.target.value})}
                         placeholder="e.g., Monthly Meeting Reminder" 
                         className="bg-background"
                       />
                    </div>
                    <div className="space-y-2">
                       <Label>Email Subject</Label>
                       <Input 
                         value={formData.subject} 
                         onChange={(e) => setFormData({...formData, subject: e.target.value})}
                         placeholder="Subject line... (use variables like {{client_name}})" 
                         className="bg-background"
                       />
                    </div>
                    <div className="space-y-2">
                       <Label>Email Body</Label>
                       <Textarea
                           value={formData.body}
                           onChange={(e) => setFormData({...formData, body: e.target.value})}
                           className="min-h-[300px] bg-background font-mono text-sm"
                           placeholder="Email body content..."
                       />
                    </div>
                 </div>

                 <div className="bg-background p-4 rounded-lg border h-fit shadow-sm">
                    <h4 className="font-semibold mb-3 text-sm">Available Variables</h4>
                    <p className="text-xs text-muted-foreground mb-4">Click to append to body.</p>
                    <div className="space-y-2">
                       {AVAILABLE_VARIABLES.map(v => (
                          <div 
                              key={v.key} 
                              className="flex items-center justify-between p-2 bg-muted rounded border text-sm hover:border-primary/30 hover:bg-accent cursor-pointer group transition-colors"
                              onClick={() => insertVariable(v.key)}
                          >
                              <div className="flex flex-col">
                                <code className="text-primary text-xs font-bold">{"{{" + v.key + "}}"}</code>
                                <span className="text-xs text-muted-foreground">{v.desc}</span>
                              </div>
                              <Plus className="w-4 h-4 opacity-0 group-hover:opacity-100 text-primary" />
                          </div>
                       ))}
                    </div>
                 </div>
               </div>
            </TabsContent>

            <TabsContent value="preview" className="flex-1 p-0 m-0 overflow-hidden relative min-h-0 bg-muted">
               <div className="absolute inset-0 flex flex-col">
                 <div className="p-2 bg-amber-50 text-amber-800 text-xs text-center border-b shrink-0">
                   Previewing with sample data. Variables will be replaced with actual values when sent.
                 </div>
                 <div className="flex-1 overflow-auto p-6">
                   <div className="bg-background rounded-lg border p-6 shadow-sm max-w-2xl mx-auto">
                     <h3 className="font-semibold mb-4 text-lg border-b pb-2">{formData.subject || 'No Subject'}</h3>
                     <div className="prose max-w-none text-sm" dangerouslySetInnerHTML={{ __html: getPreviewHtml() }} />
                   </div>
                 </div>
               </div>
            </TabsContent>
          </Tabs>
        </div>

        <DialogFooter className="p-4 border-t bg-background shrink-0">
           <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
           <Button onClick={handleSubmit} disabled={isSubmitting}>
              {isSubmitting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              {template ? 'Update Template' : 'Create Template'}
           </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
