import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsCard } from '../../components/SettingsCard';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { RefreshCw, Mail, MessageCircle, Send, Bell, Settings } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';

interface NotificationEvent {
  id: string;
  label: string;
  description: string;
  category: string;
  enabled: boolean;
  channels: {
    [channelId: string]: {
      enabled: boolean;
      recipient: 'admin' | 'customer' | 'both';
    };
  };
}

interface NotificationChannel {
  id: string;
  label: string;
  icon: string;
  enabled: boolean;
  builtin?: boolean;
  addon?: string;
}

export default function CustomerEvents() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  // Fetch customer events
  const { data: eventsData, isLoading: eventsLoading } = useQuery({
    queryKey: ['notification-customer-events'],
    queryFn: () => api.get('/notifications/customer/events'),
  });

  // Fetch channels
  const { data: channels, isLoading: channelsLoading } = useQuery({
    queryKey: ['notification-channels'],
    queryFn: () => api.get('/notifications/channels'),
  });

  // Update event mutation
  const updateMutation = useMutation({
    mutationFn: async ({ eventId, channelId, enabled, recipient }: any) => {
      return api.post('/notifications/events/update', {
        eventId,
        channelId,
        enabled,
        recipient,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-customer-events'] });
      toast.success(__('Event settings updated'));
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to update event'));
    },
  });

  const getChannelIcon = (channelId: string) => {
    switch (channelId) {
      case 'email':
        return <Mail className="h-4 w-4" />;
      case 'push':
        return <Bell className="h-4 w-4" />;
      case 'whatsapp':
        return <MessageCircle className="h-4 w-4" />;
      case 'telegram':
        return <Send className="h-4 w-4" />;
      default:
        return <Bell className="h-4 w-4" />;
    }
  };

  const handleToggle = (eventId: string, channelId: string, currentEnabled: boolean, recipient: string) => {
    updateMutation.mutate({
      eventId,
      channelId,
      enabled: !currentEnabled,
      recipient,
    });
  };

  const openTemplateEditor = (eventId: string, channelId: string) => {
    navigate(`/settings/notifications/edit-template?event=${eventId}&channel=${channelId}&recipient=customer`);
  };

  if (eventsLoading || channelsLoading) {
    return (
      <div className="flex items-center justify-center p-8">
        <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const events = eventsData || {};
  const enabledChannels = (channels || []).filter((c: NotificationChannel) => c.enabled);

  return (
    <div className="space-y-6">
      {Object.entries(events).map(([category, categoryEvents]: [string, any]) => (
        <SettingsCard
          key={category}
          title={category.charAt(0).toUpperCase() + category.slice(1)}
          description={__(`Manage ${category} notification events for customers`)}
        >
          <div className="space-y-4">
            {(categoryEvents as NotificationEvent[]).map((event) => (
              <div key={event.id} className="border-b last:border-0 pb-4 last:pb-0">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h4 className="font-medium">{event.label}</h4>
                    <p className="text-sm text-muted-foreground">{event.description}</p>
                  </div>
                </div>

                <div className="space-y-3">
                  {enabledChannels.map((channel: NotificationChannel) => {
                    const channelSettings = event.channels[channel.id];
                    const isEnabled = channelSettings?.enabled || false;
                    const recipient = channelSettings?.recipient || 'customer';

                    return (
                      <div key={channel.id} className="flex items-center justify-between p-3 rounded-lg border bg-card">
                        <div className="flex items-center gap-3">
                          <div className={`p-2 rounded-lg ${isEnabled ? 'bg-green-500/20 text-green-600' : 'bg-muted text-muted-foreground'}`}>
                            {getChannelIcon(channel.id)}
                          </div>
                          <div>
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-medium">{channel.label}</span>
                              {channel.builtin && (
                                <Badge variant="secondary" className="text-xs">
                                  {__('Built-in')}
                                </Badge>
                              )}
                            </div>
                            {isEnabled && (
                              <span className="text-xs text-muted-foreground">
                                {__('Send to')}: {recipient === 'admin' ? __('Admin') : recipient === 'customer' ? __('Customer') : __('Both')}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          {isEnabled && channel.enabled && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openTemplateEditor(event.id, channel.id)}
                              className="h-8 w-8 p-0"
                            >
                              <Settings className="h-4 w-4" />
                            </Button>
                          )}
                          <Switch
                            checked={isEnabled}
                            onCheckedChange={() => handleToggle(event.id, channel.id, isEnabled, recipient)}
                            disabled={updateMutation.isPending}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </SettingsCard>
      ))}

      {Object.keys(events).length === 0 && (
        <SettingsCard
          title={__('No Events')}
          description={__('No customer notification events configured')}
        >
          <p className="text-sm text-muted-foreground">
            {__('Customer notification events will appear here once configured.')}
          </p>
        </SettingsCard>
      )}
    </div>
  );
}
