import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsCard } from '../components/SettingsCard';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import { RefreshCw, Mail, MessageCircle, Send, Bell, Edit } from 'lucide-react';
import { __ } from '@/lib/i18n';

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

export default function NotificationTemplates() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [openAccordion, setOpenAccordion] = useState<string | undefined>();

  // Determine recipient type from current page URL (using hash because of HashRouter)
  const isStaffPage = window.location.hash.includes('/staff');
  const recipientType = isStaffPage ? 'staff' : 'customer';

  // Check for query params to open specific accordion
  useEffect(() => {
    const eventParam = searchParams.get('event');
    if (eventParam) {
      setOpenAccordion(eventParam);
    }
  }, [searchParams]);

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

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

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

  const openEditor = (event: any, channel: any) => {
    // Navigate to edit template subpage with recipient type
    navigate(`/settings/notifications/edit-template?event=${event.id}&channel=${channel.id}&recipient=${recipientType}`);
  };

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

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

  const allEvents = [
    ...(eventsData?.orders || []),
    ...(eventsData?.products || []),
    ...(eventsData?.customers || []),
  ];

  // Filter events by recipient type
  const filteredEvents = allEvents.filter((event: any) => {
    // Check both recipients array (from get_events) and recipient_type (from get_all_events)
    if (event.recipients && Array.isArray(event.recipients)) {
      return event.recipients.includes(recipientType);
    }
    return event.recipient_type === recipientType;
  });

  return (
    <div className="space-y-6">
      {/* Info Card */}
      <SettingsCard
        title={__('Notification Templates')}
        description={__('Customize notification templates for each channel')}
      >
        <div className="text-sm space-y-3">
          <p className="text-muted-foreground">
            {__(
              'Templates define the content and format of notifications sent through each channel. Customize the message, subject, and variables for each notification type.'
            )}
          </p>
          <div className="bg-muted/50 rounded-lg p-4">
            <p className="text-xs text-muted-foreground">
              💡 {__('Tip: Use variables like {customer_name}, {order_number}, and {order_total} to personalize your notifications.')}
            </p>
          </div>
        </div>
      </SettingsCard>

      {/* Templates by Channel - Accordion */}
      <SettingsCard
        title={__('Templates by Channel')}
        description={__('Customize notification templates for each channel')}
      >
        <Accordion type="single" collapsible className="w-full" value={openAccordion} onValueChange={setOpenAccordion}>
          {channels?.map((channel: NotificationChannel) => {
            const channelTemplates = filteredEvents.filter((event: any) => {
              const templateKey = `${event.id}_${channel.id}`;
              return templates && templates[templateKey];
            });
            const customCount = channelTemplates.length;

            return (
              <AccordionItem key={channel.id} value={channel.id} className="border-b">
                <AccordionTrigger className="hover:no-underline py-4">
                  <div className="flex items-center gap-3 flex-1 min-w-0">
                    <div className="p-2 rounded-lg bg-primary/10 shrink-0">{getChannelIcon(channel.id)}</div>
                    <div className="flex flex-col sm:flex-row sm:items-center gap-2 flex-1 min-w-0">
                      <span className="font-medium text-left">{channel.label}</span>
                      <div className="flex items-center gap-2 flex-wrap">
                        <Badge variant="secondary" className="text-xs">
                          {filteredEvents.length} {__('templates')}
                        </Badge>
                        {customCount > 0 && (
                          <Badge variant="default" className="text-xs">
                            {customCount} {__('custom')}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                </AccordionTrigger>
                <AccordionContent>
                  <div className="space-y-2 pt-2">
                    {filteredEvents.map((event: any) => {
                      const templateKey = `${event.id}_${channel.id}`;
                      const hasCustomTemplate = templates && templates[templateKey];

                      return (
                        <div
                          key={`${event.id}_${channel.id}`}
                          className="flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
                        >
                          <div className="flex items-center gap-3 flex-1">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <h4 className="font-medium text-sm">{event.label}</h4>
                                {hasCustomTemplate && (
                                  <Badge variant="default" className="text-xs">
                                    {__('Custom')}
                                  </Badge>
                                )}
                              </div>
                              <p className="text-xs text-muted-foreground">{event.description}</p>
                            </div>
                          </div>
                          <Button variant="outline" size="sm" onClick={() => openEditor(event, channel)}>
                            <Edit className="h-4 w-4 mr-2" />
                            {__('Edit')}
                          </Button>
                        </div>
                      );
                    })}
                  </div>
                </AccordionContent>
              </AccordionItem>
            );
          })}
        </Accordion>
      </SettingsCard>
    </div>
  );
}
