import { Code, Eye, Mail, Plus, Save, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';

interface EmailTemplate {
  id: string;
  name: string;
  subject: string;
  type: 'welcome' | 'reset-password' | 'lead-notification' | 'trip-confirmation' | 'custom';
  content: string;
  variables: string[];
  isActive: boolean;
  updatedAt: string;
}

export default function EmailTemplates() {
  const { toast } = useToast();
  const [templates] = useState<EmailTemplate[]>([
    {
      id: '1',
      name: 'Hoş Geldiniz E-postası',
      subject: 'LetsGoCappadocia\'ya Hoş Geldiniz!',
      type: 'welcome',
      content: 'Merhaba {{username}},\n\nLetsGoCappadocia ailesine hoş geldiniz!',
      variables: ['username', 'email'],
      isActive: true,
      updatedAt: '2026-01-10T10:00:00Z',
    },
    {
      id: '2',
      name: 'Şifre Sıfırlama',
      subject: 'Şifre Sıfırlama Talebi',
      type: 'reset-password',
      content: 'Merhaba {{username}},\n\nŞifre sıfırlama bağlantınız: {{reset_link}}',
      variables: ['username', 'reset_link'],
      isActive: true,
      updatedAt: '2026-01-09T15:30:00Z',
    },
    {
      id: '3',
      name: 'Lead Bildirimi',
      subject: 'Yeni Lead Aldınız',
      type: 'lead-notification',
      content: 'Merhaba {{provider_name}},\n\nYeni bir lead aldınız: {{lead_details}}',
      variables: ['provider_name', 'lead_details', 'lead_id'],
      isActive: true,
      updatedAt: '2026-01-08T12:00:00Z',
    },
  ]);

  const [open, setOpen] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplate | null>(null);

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'welcome':
        return 'Hoş Geldiniz';
      case 'reset-password':
        return 'Şifre Sıfırlama';
      case 'lead-notification':
        return 'Lead Bildirimi';
      case 'trip-confirmation':
        return 'Seyahat Onayı';
      case 'custom':
        return 'Özel';
      default:
        return type;
    }
  };

  const handlePreview = (template: EmailTemplate) => {
    setSelectedTemplate(template);
    setPreviewOpen(true);
  };

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">E-posta Şablonları</h1>
          <p className="text-muted-foreground mt-1">
            Sistem e-posta şablonlarını yönetin
          </p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Yeni Şablon
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Yeni E-posta Şablonu</DialogTitle>
              <DialogDescription>
                Yeni bir e-posta şablonu oluşturun
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="name">Şablon Adı</Label>
                <Input id="name" placeholder="Şablon adı" />
              </div>
              <div>
                <Label htmlFor="type">Tip</Label>
                <Select defaultValue="custom">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="welcome">Hoş Geldiniz</SelectItem>
                    <SelectItem value="reset-password">Şifre Sıfırlama</SelectItem>
                    <SelectItem value="lead-notification">Lead Bildirimi</SelectItem>
                    <SelectItem value="trip-confirmation">Seyahat Onayı</SelectItem>
                    <SelectItem value="custom">Özel</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="subject">Konu</Label>
                <Input id="subject" placeholder="E-posta konusu" />
              </div>
              <div>
                <Label htmlFor="content">İçerik</Label>
                <Textarea
                  id="content"
                  placeholder="E-posta içeriği ({{variable}} formatında değişkenler kullanabilirsiniz)"
                  rows={8}
                />
              </div>
              <div>
                <Label htmlFor="variables">Değişkenler</Label>
                <Input
                  id="variables"
                  placeholder="username, email, link (virgülle ayırın)"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Şablonda kullanılacak değişkenleri virgülle ayırarak girin
                </p>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setOpen(false)}>
                İptal
              </Button>
              <Button onClick={() => {
                toast({
                  title: 'Şablon Kaydedildi',
                  description: 'E-posta şablonu başarıyla kaydedildi.',
                });
                setOpen(false);
              }}>
                <Save className="h-4 w-4 mr-2" />
                Kaydet
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Toplam Şablon</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{templates.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Aktif</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {templates.filter((t) => t.isActive).length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Pasif</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {templates.filter((t) => !t.isActive).length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Özel Şablonlar</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {templates.filter((t) => t.type === 'custom').length}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Templates List */}
      <Card>
        <CardHeader>
          <CardTitle>E-posta Şablonları</CardTitle>
          <CardDescription>Tüm e-posta şablonlarının listesi</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {templates.map((template) => (
              <div
                key={template.id}
                className="flex items-start justify-between p-4 border rounded-lg"
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <h3 className="font-semibold">{template.name}</h3>
                    <Badge variant="outline">{getTypeLabel(template.type)}</Badge>
                    <Badge variant={template.isActive ? 'default' : 'secondary'}>
                      {template.isActive ? 'Aktif' : 'Pasif'}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground mb-2">
                    <strong>Konu:</strong> {template.subject}
                  </p>
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    <Code className="h-3 w-3" />
                    <span>Değişkenler: {template.variables.join(', ')}</span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    Son güncelleme: {new Date(template.updatedAt).toLocaleString('tr-TR')}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePreview(template)}
                  >
                    <Eye className="h-4 w-4 mr-2" />
                    Önizle
                  </Button>
                  <Button variant="ghost" size="icon">
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Preview Dialog */}
      <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Şablon Önizleme</DialogTitle>
            <DialogDescription>
              {selectedTemplate?.name}
            </DialogDescription>
          </DialogHeader>
          {selectedTemplate && (
            <div className="space-y-4">
              <div>
                <Label>Konu</Label>
                <div className="p-3 bg-muted rounded-lg mt-1">
                  {selectedTemplate.subject}
                </div>
              </div>
              <div>
                <Label>İçerik</Label>
                <div className="p-3 bg-muted rounded-lg mt-1 whitespace-pre-wrap">
                  {selectedTemplate.content}
                </div>
              </div>
              <div>
                <Label>Kullanılabilir Değişkenler</Label>
                <div className="flex flex-wrap gap-2 mt-1">
                  {selectedTemplate.variables.map((variable) => (
                    <Badge key={variable} variant="secondary">
                      {`{{${variable}}}`}
                    </Badge>
                  ))}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setPreviewOpen(false)}>
              Kapat
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
