
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 { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { Loader2 } from 'lucide-react';

const AVAILABLE_VARIABLES = [
  { key: '{ownerName}', description: "Owner's Full Name" },
  { key: '{propertyAddress}', description: 'Property Address' },
  { key: '{date}', description: 'Current Date' },
  { key: '{subject}', description: 'Email Subject' },
  { key: '{message}', description: 'Custom Message' }
];

export default function OwnerNotificationTemplateDialog({ open, onOpenChange, template, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({ name: '', subject: '', body: '' });

  useEffect(() => {
    if (open) {
      if (template) {
        setFormData({ name: template.name || '', subject: template.subject || '', body: template.body || '' });
      } else {
        setFormData({ name: '', subject: '', body: '' });
      }
    }
  }, [open, template]);

  const handleChange = (e) => setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  const insertVariable = (variable) => setFormData(prev => ({ ...prev, body: prev.body + variable }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.name || !formData.subject || !formData.body) {
      toast({ variant: 'destructive', title: 'Error', description: 'All fields are required.' });
      return;
    }

    setLoading(true);
    try {
      if (template?.id) {
        const { error } = await supabase
          .from('owner_notification_templates')
          .update({ name: formData.name, subject: formData.subject, body: formData.body, updated_at: new Date().toISOString() })
          .eq('id', template.id);
        if (error) throw error;
        toast({ title: 'Success', description: 'Template updated.' });
      } else {
        const { error } = await supabase
          .from('owner_notification_templates')
          .insert([{ name: formData.name, subject: formData.subject, body: formData.body, created_by: user.id }]);
        if (error) throw error;
        toast({ title: 'Success', description: 'Template created.' });
      }
      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error(error);
      toast({ variant: 'destructive', title: 'Error', description: error.message });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{template ? 'Edit Template' : 'New Template'}</DialogTitle>
          <DialogDescription>Create a reusable email template for owner notifications.</DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label>Template Name</Label>
            <Input name="name" value={formData.name} onChange={handleChange} placeholder="e.g., Monthly Meeting Notice" />
          </div>
          <div className="space-y-2">
            <Label>Email Subject</Label>
            <Input name="subject" value={formData.subject} onChange={handleChange} placeholder="Subject line..." />
          </div>
          <div className="space-y-2">
            <Label>Email Body</Label>
            <div className="flex flex-wrap gap-2 mb-2 p-2 bg-muted rounded border">
                <span className="text-xs text-muted-foreground w-full mb-1">Available Variables: (Click to insert)</span>
                {AVAILABLE_VARIABLES.map(v => (
                    <Button key={v.key} type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => insertVariable(v.key)} title={v.description}>
                        {v.key}
                    </Button>
                ))}
            </div>
            <Textarea name="body" value={formData.body} onChange={handleChange} className="min-h-[250px] font-mono text-sm" placeholder="Dear {ownerName}," />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>
              {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
              {template ? 'Update Template' : 'Create Template'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
