import { Activity, Plus, Trash2, Webhook as WebhookIcon } 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 { useToast } from '@/hooks/use-toast';

interface Webhook {
  id: string;
  name: string;
  url: string;
  events: string[];
  isActive: boolean;
  createdAt: string;
  lastTriggered?: string;
  successCount: number;
  failureCount: number;
}

export default function Webhooks() {
  const { toast } = useToast();
  const [webhooks] = useState<Webhook[]>([
    {
      id: '1',
      name: 'Lead Notification Webhook',
      url: 'https://example.com/webhooks/leads',
      events: ['lead.created', 'lead.updated'],
      isActive: true,
      createdAt: '2026-01-01T10:00:00Z',
      lastTriggered: '2026-01-15T14:30:00Z',
      successCount: 1234,
      failureCount: 5,
    },
    {
      id: '2',
      name: 'Trip Confirmation Webhook',
      url: 'https://example.com/webhooks/trips',
      events: ['trip.created', 'trip.completed'],
      isActive: true,
      createdAt: '2025-12-15T09:00:00Z',
      lastTriggered: '2026-01-14T11:20:00Z',
      successCount: 567,
      failureCount: 2,
    },
  ]);

  const [open, setOpen] = useState(false);

  const availableEvents = [
    { value: 'lead.created', label: 'Lead Oluşturuldu' },
    { value: 'lead.updated', label: 'Lead Güncellendi' },
    { value: 'lead.deleted', label: 'Lead Silindi' },
    { value: 'trip.created', label: 'Seyahat Oluşturuldu' },
    { value: 'trip.updated', label: 'Seyahat Güncellendi' },
    { value: 'trip.completed', label: 'Seyahat Tamamlandı' },
    { value: 'user.registered', label: 'Kullanıcı Kaydoldu' },
    { value: 'provider.registered', label: 'Sağlayıcı Kaydoldu' },
  ];

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Webhooks</h1>
          <p className="text-muted-foreground mt-1">
            Sistem olayları için webhook entegrasyonlarını yönetin
          </p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Yeni Webhook
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Yeni Webhook Oluştur</DialogTitle>
              <DialogDescription>
                Sistem olayları için yeni bir webhook endpoint ekleyin
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="name">Webhook Adı</Label>
                <Input id="name" placeholder="örn: Lead Notification Webhook" />
              </div>
              <div>
                <Label htmlFor="url">Endpoint URL</Label>
                <Input id="url" placeholder="https://example.com/webhooks/endpoint" />
              </div>
              <div>
                <Label htmlFor="events">Olaylar</Label>
                <Select defaultValue="lead.created">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {availableEvents.map((event) => (
                      <SelectItem key={event.value} value={event.value}>
                        {event.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground mt-1">
                  Webhook'un dinleyeceği olayları seçin
                </p>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setOpen(false)}>
                İptal
              </Button>
              <Button
                onClick={() => {
                  toast({
                    title: 'Webhook Oluşturuldu',
                    description: 'Yeni webhook başarıyla oluşturuldu.',
                  });
                  setOpen(false);
                }}
              >
                <WebhookIcon className="h-4 w-4 mr-2" />
                Oluştur
              </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 Webhook</CardTitle>
            <WebhookIcon className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{webhooks.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>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {webhooks.filter((w) => w.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">Başarılı İstek</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {webhooks.reduce((sum, w) => sum + w.successCount, 0)}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Başarısız İstek</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {webhooks.reduce((sum, w) => sum + w.failureCount, 0)}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Webhooks List */}
      <Card>
        <CardHeader>
          <CardTitle>Webhook Listesi</CardTitle>
          <CardDescription>Tüm webhook entegrasyonlarının listesi</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {webhooks.map((webhook) => (
              <div
                key={webhook.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">{webhook.name}</h3>
                    <Badge variant={webhook.isActive ? 'default' : 'secondary'}>
                      {webhook.isActive ? 'Aktif' : 'Pasif'}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground mb-2">
                    <strong>URL:</strong> {webhook.url}
                  </p>
                  <div className="flex flex-wrap gap-1 mb-2">
                    {webhook.events.map((event) => (
                      <Badge key={event} variant="outline" className="text-xs">
                        {event}
                      </Badge>
                    ))}
                  </div>
                  <div className="grid grid-cols-2 gap-4 text-xs text-muted-foreground">
                    <div>
                      <p>Başarılı: {webhook.successCount}</p>
                      <p>Başarısız: {webhook.failureCount}</p>
                    </div>
                    <div>
                      <p>Oluşturulma: {new Date(webhook.createdAt).toLocaleDateString('tr-TR')}</p>
                      {webhook.lastTriggered && (
                        <p>
                          Son tetikleme:{' '}
                          {new Date(webhook.lastTriggered).toLocaleString('tr-TR')}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
                <Button variant="ghost" size="icon" className="text-destructive">
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Documentation */}
      <Card>
        <CardHeader>
          <CardTitle>Webhook Dokümantasyonu</CardTitle>
          <CardDescription>Webhook kullanımı hakkında bilgi</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <h4 className="font-semibold mb-2">Payload Formatı</h4>
            <p className="text-sm text-muted-foreground mb-2">
              Webhook istekleri aşağıdaki JSON formatında gönderilir:
            </p>
            <code className="block bg-muted p-3 rounded text-sm whitespace-pre">
              {`{
  "event": "lead.created",
  "timestamp": "2026-01-15T14:30:00Z",
  "data": {
    "id": "123",
    "type": "lead",
    ...
  }
}`}
            </code>
          </div>
          <div>
            <h4 className="font-semibold mb-2">Güvenlik</h4>
            <p className="text-sm text-muted-foreground">
              Webhook istekleri X-Webhook-Signature header ile imzalanır. İmzayı doğrulamak için
              webhook secret kullanın.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
