import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { ExternalLink, RefreshCw, Mail } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';

export default function NotificationsSettings() {
  const queryClient = useQueryClient();
  const wcAdminUrl = (window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin';

  // Fetch email settings
  const { data: settings, isLoading, refetch } = useQuery({
    queryKey: ['email-settings'],
    queryFn: () => api.get('/settings/emails'),
  });

  // Toggle email mutation
  const toggleMutation = useMutation({
    mutationFn: async ({ emailId, enabled }: { emailId: string; enabled: boolean }) => {
      return api.post(`/settings/emails/${emailId}/toggle`, { enabled });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-settings'] });
      toast.success(__('Email settings updated'));
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to update email settings'));
    },
  });

  if (isLoading) {
    return (
      <SettingsLayout
        title={__('Notifications')}
        description={__('Manage email notifications sent to customers and admins')}
      >
        <div className="flex items-center justify-center py-12">
          <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      </SettingsLayout>
    );
  }

  const customerEmails = settings?.emails?.filter((e: any) => e.recipient === 'customer') || [];
  const adminEmails = settings?.emails?.filter((e: any) => e.recipient === 'admin') || [];

  return (
    <SettingsLayout
      title={__('Notifications')}
      description={__('Manage email notifications sent to customers and admins')}
      action={
        <Button
          variant="outline"
          size="sm"
          onClick={() => refetch()}
        >
          <RefreshCw className="h-4 w-4 mr-2" />
          {__('Refresh')}
        </Button>
      }
    >
      <div className="space-y-6">
        {/* Info Card - Shopify/Marketplace Style */}
        <SettingsCard
          title={__('Email Notifications')}
          description={__('Manage automated emails sent to customers and admins')}
        >
          <div className="text-sm space-y-3">
            <p className="text-muted-foreground">
              {__('Control which email notifications are sent automatically when orders are placed, shipped, or updated. All emails use your store branding and can be customized in WooCommerce settings.')}
            </p>
            
            <div className="bg-muted/50 rounded-lg p-4 space-y-2">
              <p className="font-medium text-foreground text-sm">
                💡 {__('Quick Tips')}
              </p>
              <ul className="text-xs text-muted-foreground space-y-1.5">
                <li>• {__('Keep order confirmation emails enabled - customers expect immediate confirmation')}</li>
                <li>• {__('Enable shipping notifications to reduce "where is my order?" inquiries')}</li>
                <li>• {__('Admin notifications help you stay on top of new orders and issues')}</li>
                <li>• {__('Disable emails you don\'t need to reduce inbox clutter')}</li>
              </ul>
            </div>

            <div className="pt-2">
              <p className="text-xs text-muted-foreground">
                {__('Need to customize email templates, subject lines, or sender details?')}{' '}
                <a 
                  href={`${(window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin'}/admin.php?page=wc-settings&tab=email`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-primary hover:underline"
                >
                  {__('Go to advanced email settings →')}
                </a>
              </p>
            </div>
          </div>
        </SettingsCard>

        {/* Customer Emails */}
        <SettingsCard
          title={__('Customer Notifications')}
          description={__('Emails sent to customers about their orders')}
        >
          <div className="space-y-4">
            {customerEmails.map((email: any) => (
              <div key={email.id} className="flex items-center justify-between py-3 border-b last:border-0">
                <div className="flex-1">
                  <h3 className="font-medium text-sm">{email.title}</h3>
                  <p className="text-xs text-muted-foreground mt-0.5">{email.description}</p>
                </div>
                <Switch
                  checked={email.enabled === 'yes'}
                  onCheckedChange={(checked) => toggleMutation.mutate({ 
                    emailId: email.id, 
                    enabled: checked 
                  })}
                  disabled={toggleMutation.isPending}
                />
              </div>
            ))}
          </div>
        </SettingsCard>

        {/* Admin Emails */}
        <SettingsCard
          title={__('Admin Notifications')}
          description={__('Emails sent to store administrators')}
        >
          <div className="space-y-4">
            {adminEmails.map((email: any) => (
              <div key={email.id} className="flex items-center justify-between py-3 border-b last:border-0">
                <div className="flex-1">
                  <h3 className="font-medium text-sm">{email.title}</h3>
                  <p className="text-xs text-muted-foreground mt-0.5">{email.description}</p>
                </div>
                <Switch
                  checked={email.enabled === 'yes'}
                  onCheckedChange={(checked) => toggleMutation.mutate({ 
                    emailId: email.id, 
                    enabled: checked 
                  })}
                  disabled={toggleMutation.isPending}
                />
              </div>
            ))}
          </div>
        </SettingsCard>

      </div>
    </SettingsLayout>
  );
}
