import { useEffect, useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { RichTextEditor } from '@/components/RichTextEditor';
import { toast } from '@/hooks/use-toast';
import { Mail, AlertTriangle, Send, ChevronDown, ChevronUp, Webhook } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';

interface SmtpSettings {
  id?: string;
  smtp_host: string;
  smtp_port: number;
  smtp_username: string;
  smtp_password: string;
  smtp_from_name: string;
  smtp_from_email: string;
  smtp_use_tls: boolean;
}

interface NotificationTemplate {
  id: string;
  key: string;
  name: string;
  is_active: boolean;
  email_subject: string;
  email_body_html: string;
  webhook_url: string;
  last_payload_example: Record<string, unknown> | null;
}

const SHORTCODES_HELP = {
  common: ['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}'],
  access: ['{produk}', '{link_akses}'],
  consulting: ['{tanggal_konsultasi}', '{jam_konsultasi}', '{link_meet}'],
  event: ['{judul_event}', '{tanggal_event}', '{jam_event}', '{link_event}'],
};

const DEFAULT_TEMPLATES = [
  { key: 'payment_success', name: 'Pembayaran Berhasil' },
  { key: 'access_granted', name: 'Akses Produk Diberikan' },
  { key: 'order_created', name: 'Pesanan Dibuat' },
  { key: 'payment_reminder', name: 'Pengingat Pembayaran' },
  { key: 'consulting_scheduled', name: 'Konsultasi Terjadwal' },
  { key: 'event_reminder', name: 'Reminder Webinar/Bootcamp' },
  { key: 'bootcamp_progress', name: 'Progress Bootcamp' },
];

const emptySmtp: SmtpSettings = {
  smtp_host: '',
  smtp_port: 587,
  smtp_username: '',
  smtp_password: '',
  smtp_from_name: '',
  smtp_from_email: '',
  smtp_use_tls: true,
};

export function NotifikasiTab() {
  const [smtp, setSmtp] = useState<SmtpSettings>(emptySmtp);
  const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testEmail, setTestEmail] = useState('');
  const [expandedTemplates, setExpandedTemplates] = useState<Set<string>>(new Set());

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    // Fetch SMTP settings
    const { data: smtpData } = await supabase.from('notification_settings').select('*').single();
    if (smtpData) setSmtp(smtpData);

    // Fetch templates
    const { data: templatesData } = await supabase.from('notification_templates').select('*').order('key');
    if (templatesData && templatesData.length > 0) {
      setTemplates(templatesData);
    } else {
      // Seed default templates if none exist
      await seedTemplates();
    }
    setLoading(false);
  };

  const seedTemplates = async () => {
    const toInsert = DEFAULT_TEMPLATES.map(t => ({
      key: t.key,
      name: t.name,
      is_active: false,
      email_subject: '',
      email_body_html: '',
      webhook_url: '',
    }));
    const { data, error } = await supabase.from('notification_templates').insert(toInsert).select();
    if (!error && data) setTemplates(data);
  };

  const saveSmtp = async () => {
    setSaving(true);
    const payload = { ...smtp };
    delete payload.id;

    if (smtp.id) {
      const { error } = await supabase.from('notification_settings').update(payload).eq('id', smtp.id);
      if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' });
      else toast({ title: 'Berhasil', description: 'Pengaturan SMTP disimpan' });
    } else {
      const { data, error } = await supabase.from('notification_settings').insert(payload).select().single();
      if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' });
      else { setSmtp(data); toast({ title: 'Berhasil', description: 'Pengaturan SMTP disimpan' }); }
    }
    setSaving(false);
  };

  const sendTestEmail = async () => {
    if (!testEmail) return toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' });
    console.log('Test email would be sent to:', testEmail, 'with SMTP config:', smtp);
    toast({ title: 'Info', description: `Email uji coba akan dikirim ke ${testEmail} (fitur sedang dikembangkan)` });
  };

  const updateTemplate = async (template: NotificationTemplate) => {
    const { id, key, name, ...updates } = template;
    const { error } = await supabase.from('notification_templates').update(updates).eq('id', id);
    if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' });
    else toast({ title: 'Berhasil', description: `Template "${name}" disimpan` });
  };

  const toggleExpand = (id: string) => {
    setExpandedTemplates(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const isSmtpConfigured = smtp.smtp_host && smtp.smtp_username && smtp.smtp_password;

  if (loading) return <div className="animate-pulse h-64 bg-muted rounded-md" />;

  return (
    <div className="space-y-6">
      {/* SMTP Settings */}
      <Card className="border-2 border-border">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="w-5 h-5" />
            Pengaturan SMTP
          </CardTitle>
          <CardDescription>Konfigurasi server email untuk pengiriman notifikasi</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {!isSmtpConfigured && (
            <Alert variant="destructive" className="border-2">
              <AlertTriangle className="w-4 h-4" />
              <AlertDescription>
                Konfigurasi SMTP belum lengkap. Email tidak akan terkirim.
              </AlertDescription>
            </Alert>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>SMTP Host</Label>
              <Input
                value={smtp.smtp_host}
                onChange={(e) => setSmtp({ ...smtp, smtp_host: e.target.value })}
                placeholder="smtp.example.com"
                className="border-2"
              />
            </div>
            <div className="space-y-2">
              <Label>SMTP Port</Label>
              <Input
                type="number"
                value={smtp.smtp_port}
                onChange={(e) => setSmtp({ ...smtp, smtp_port: parseInt(e.target.value) || 587 })}
                className="border-2"
              />
            </div>
            <div className="space-y-2">
              <Label>Username</Label>
              <Input
                value={smtp.smtp_username}
                onChange={(e) => setSmtp({ ...smtp, smtp_username: e.target.value })}
                className="border-2"
              />
            </div>
            <div className="space-y-2">
              <Label>Password</Label>
              <Input
                type="password"
                value={smtp.smtp_password}
                onChange={(e) => setSmtp({ ...smtp, smtp_password: e.target.value })}
                className="border-2"
              />
            </div>
            <div className="space-y-2">
              <Label>Nama Pengirim</Label>
              <Input
                value={smtp.smtp_from_name}
                onChange={(e) => setSmtp({ ...smtp, smtp_from_name: e.target.value })}
                placeholder="Nama Bisnis"
                className="border-2"
              />
            </div>
            <div className="space-y-2">
              <Label>Email Pengirim</Label>
              <Input
                type="email"
                value={smtp.smtp_from_email}
                onChange={(e) => setSmtp({ ...smtp, smtp_from_email: e.target.value })}
                placeholder="noreply@example.com"
                className="border-2"
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <Switch
              checked={smtp.smtp_use_tls}
              onCheckedChange={(checked) => setSmtp({ ...smtp, smtp_use_tls: checked })}
            />
            <Label>Gunakan TLS/SSL</Label>
          </div>

          <div className="flex gap-4 pt-4 border-t">
            <Button onClick={saveSmtp} disabled={saving}>
              {saving ? 'Menyimpan...' : 'Simpan'}
            </Button>
            <div className="flex gap-2 flex-1">
              <Input
                type="email"
                value={testEmail}
                onChange={(e) => setTestEmail(e.target.value)}
                placeholder="Email uji coba"
                className="border-2 max-w-xs"
              />
              <Button variant="outline" onClick={sendTestEmail} className="border-2">
                <Send className="w-4 h-4 mr-2" />
                Kirim Email Uji Coba
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Notification Templates */}
      <Card className="border-2 border-border">
        <CardHeader>
          <CardTitle>Template Notifikasi</CardTitle>
          <CardDescription>
            Atur template email untuk berbagai jenis notifikasi
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="text-sm text-muted-foreground p-3 bg-muted rounded-md">
            <p className="font-medium mb-2">Shortcode yang tersedia:</p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              <div>
                <span className="font-medium">Umum:</span> {SHORTCODES_HELP.common.join(', ')}
              </div>
              <div>
                <span className="font-medium">Akses:</span> {SHORTCODES_HELP.access.join(', ')}
              </div>
              <div>
                <span className="font-medium">Konsultasi:</span> {SHORTCODES_HELP.consulting.join(', ')}
              </div>
              <div>
                <span className="font-medium">Event:</span> {SHORTCODES_HELP.event.join(', ')}
              </div>
            </div>
          </div>

          {templates.map((template) => (
            <Collapsible
              key={template.id}
              open={expandedTemplates.has(template.id)}
              onOpenChange={() => toggleExpand(template.id)}
            >
              <div className="border-2 border-border rounded-lg">
                <CollapsibleTrigger asChild>
                  <div className="flex items-center justify-between p-4 cursor-pointer hover:bg-muted/50">
                    <div className="flex items-center gap-4">
                      <Switch
                        checked={template.is_active}
                        onCheckedChange={(checked) => {
                          const updated = { ...template, is_active: checked };
                          setTemplates(templates.map(t => t.id === template.id ? updated : t));
                          updateTemplate(updated);
                        }}
                        onClick={(e) => e.stopPropagation()}
                      />
                      <div>
                        <p className="font-medium">{template.name}</p>
                        <p className="text-sm text-muted-foreground">{template.key}</p>
                      </div>
                    </div>
                    {expandedTemplates.has(template.id) ? (
                      <ChevronUp className="w-5 h-5" />
                    ) : (
                      <ChevronDown className="w-5 h-5" />
                    )}
                  </div>
                </CollapsibleTrigger>

                <CollapsibleContent>
                  <div className="p-4 pt-0 space-y-4 border-t">
                    <div className="space-y-2">
                      <Label>Subjek Email</Label>
                      <Input
                        value={template.email_subject}
                        onChange={(e) => {
                          setTemplates(templates.map(t =>
                            t.id === template.id ? { ...t, email_subject: e.target.value } : t
                          ));
                        }}
                        placeholder="Subjek email..."
                        className="border-2"
                      />
                    </div>

                    <div className="space-y-2">
                      <Label>Isi Email (HTML)</Label>
                      <RichTextEditor
                        content={template.email_body_html}
                        onChange={(html) => {
                          setTemplates(templates.map(t =>
                            t.id === template.id ? { ...t, email_body_html: html } : t
                          ));
                        }}
                        placeholder="Tulis isi email..."
                      />
                    </div>

                    <div className="space-y-2">
                      <Label className="flex items-center gap-2">
                        <Webhook className="w-4 h-4" />
                        Webhook URL (opsional, untuk n8n/Zapier)
                      </Label>
                      <Input
                        value={template.webhook_url}
                        onChange={(e) => {
                          setTemplates(templates.map(t =>
                            t.id === template.id ? { ...t, webhook_url: e.target.value } : t
                          ));
                        }}
                        placeholder="https://n8n.example.com/webhook/..."
                        className="border-2"
                      />
                    </div>

                    {template.last_payload_example && (
                      <div className="space-y-2">
                        <Label>Contoh Payload Terakhir</Label>
                        <pre className="p-3 bg-muted rounded-md text-xs overflow-x-auto">
                          {JSON.stringify(template.last_payload_example, null, 2)}
                        </pre>
                      </div>
                    )}

                    <Button
                      onClick={() => updateTemplate(template)}
                      className="shadow-sm"
                    >
                      Simpan Template
                    </Button>
                  </div>
                </CollapsibleContent>
              </div>
            </Collapsible>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
