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

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

export default function CustomerChannels() {
  const queryClient = useQueryClient();

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

  // Toggle channel mutation
  const toggleChannelMutation = useMutation({
    mutationFn: async ({ channelId, enabled }: { channelId: string; enabled: boolean }) => {
      const response = await api.post('/notifications/channels/toggle', { channelId, enabled });
      return response;
    },
    onSuccess: (data, variables) => {
      queryClient.setQueryData(['notification-channels'], (old: any) => {
        if (!old) return old;
        return old.map((channel: any) => 
          channel.id === variables.channelId 
            ? { ...channel, enabled: data.enabled } 
            : channel
        );
      });
      toast.success(__('Channel updated'));
    },
    onError: (error: any) => {
      queryClient.invalidateQueries({ queryKey: ['notification-channels'] });
      toast.error(error?.message || __('Failed to update channel'));
    },
  });

  const getChannelIcon = (channelId: string) => {
    switch (channelId) {
      case 'email':
        return <Mail className="h-6 w-6" />;
      case 'push':
        return <Bell className="h-6 w-6" />;
      case 'sms':
        return <MessageSquare className="h-6 w-6" />;
      default:
        return <Bell className="h-6 w-6" />;
    }
  };

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

  const builtinChannels = (channels || []).filter((c: NotificationChannel) => c.builtin);

  return (
    <div className="space-y-6">
      <Alert>
        <Info className="h-4 w-4" />
        <AlertDescription>
          {__('Customer notifications are sent based on order status, account activities, and customer preferences. Customers can manage their notification preferences from their account page.')}
        </AlertDescription>
      </Alert>

      <SettingsCard
        title={__('Channels')}
        description={__('Enable or disable notification channels for customers')}
      >
        <div className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-4">
          <p className="text-sm text-muted-foreground mb-2">
            💡 {__('Need to configure channel settings?')}
          </p>
          <Link to="/settings/notifications/channels">
            <Button variant="outline" size="sm" className="gap-2">
              {__('Go to Channel Configuration')}
              <ArrowRight className="h-4 w-4" />
            </Button>
          </Link>
        </div>
      </SettingsCard>

      <SettingsCard
        title={__('Available Channels')}
        description={__('Manage notification delivery channels')}
      >
        <div className="space-y-4">
          {/* Email Channel */}
          <div className="flex items-center justify-between p-4 rounded-lg border bg-card">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-lg shrink-0 bg-green-500/20 text-green-600">
                <Mail className="h-6 w-6" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="font-medium">{__('Email')}</h3>
                  <Badge variant="secondary" className="text-xs">
                    {__('Built-in')}
                  </Badge>
                </div>
                <p className="text-sm text-muted-foreground">
                  {__('Email notifications powered by WooCommerce. Configure templates and SMTP settings.')}
                </p>
              </div>
            </div>
            <Switch
              checked={channels?.find((c: any) => c.id === 'email')?.enabled ?? true}
              onCheckedChange={(checked) => {
                toggleChannelMutation.mutate({ channelId: 'email', enabled: checked });
              }}
              disabled={toggleChannelMutation.isPending}
            />
          </div>

          {/* Push Notifications */}
          <div className="flex items-center justify-between p-4 rounded-lg border bg-card">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-lg shrink-0 bg-green-500/20 text-green-600">
                <Bell className="h-6 w-6" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="font-medium">{__('Push Notifications')}</h3>
                  <Badge variant="secondary" className="text-xs">
                    {__('Built-in')}
                  </Badge>
                </div>
                <p className="text-sm text-muted-foreground">
                  {__('Browser push notifications for real-time updates. Perfect for PWA.')}
                </p>
              </div>
            </div>
            <Switch
              checked={channels?.find((c: any) => c.id === 'push')?.enabled ?? true}
              onCheckedChange={(checked) => {
                toggleChannelMutation.mutate({ channelId: 'push', enabled: checked });
              }}
              disabled={toggleChannelMutation.isPending}
            />
          </div>
        </div>
      </SettingsCard>

      {/* Extend with Addons */}
      <SettingsCard
        title={__('Extend with Addons')}
        description={__('Add more notification channels to your store')}
        className='hidden'
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            {__('Install notification addons to send notifications via WhatsApp, Telegram, SMS, and more.')}
          </p>

          <div className="grid gap-4 md:grid-cols-2">
            {/* WhatsApp Addon */}
            <div className="p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-3 mb-2">
                <MessageCircle className="h-5 w-5 text-green-600" />
                <h4 className="font-medium">{__('WhatsApp Notifications')}</h4>
              </div>
              <p className="text-sm text-muted-foreground mb-3">
                {__('Send order updates and notifications via WhatsApp Business API')}
              </p>
              <Button variant="outline" size="sm" className="w-full">
                <ExternalLink className="h-4 w-4 mr-2" />
                {__('View Addon')}
              </Button>
            </div>

            {/* Telegram Addon */}
            <div className="p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-3 mb-2">
                <Send className="h-5 w-5 text-blue-600" />
                <h4 className="font-medium">{__('Telegram Notifications')}</h4>
              </div>
              <p className="text-sm text-muted-foreground mb-3">
                {__('Get instant notifications in your Telegram channel or group')}
              </p>
              <Button variant="outline" size="sm" className="w-full">
                <ExternalLink className="h-4 w-4 mr-2" />
                {__('View Addon')}
              </Button>
            </div>

            {/* SMS Addon */}
            <div className="p-4 rounded-lg border bg-card">
              <div className="flex items-center gap-3 mb-2">
                <Bell className="h-5 w-5 text-purple-600" />
                <h4 className="font-medium">{__('SMS Notifications')}</h4>
              </div>
              <p className="text-sm text-muted-foreground mb-3">
                {__('Send SMS notifications via Twilio, Nexmo, or other providers')}
              </p>
              <Button variant="outline" size="sm" className="w-full">
                <ExternalLink className="h-4 w-4 mr-2" />
                {__('View Addon')}
              </Button>
            </div>
          </div>
        </div>
      </SettingsCard>

      <SettingsCard
        title={__('Customer Preferences')}
        description={__('How customers control their notifications')}
      >
        <div className="space-y-3 text-sm">
          <p className="text-muted-foreground">
            {__('Customers can manage their notification preferences from:')}
          </p>
          <ul className="list-disc list-inside space-y-2 text-muted-foreground pl-4">
            <li>{__('My Account → Notification Preferences')}</li>
            <li>{__('Unsubscribe links in emails')}</li>
            <li>{__('Browser push notification settings')}</li>
          </ul>
          <div className="pt-3 border-t">
            <p className="text-xs text-muted-foreground">
              {__('Note: Transactional emails (order confirmations, shipping updates) cannot be disabled by customers as they are required for order fulfillment.')}
            </p>
          </div>
        </div>
      </SettingsCard>
    </div>
  );
}
