import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { usePublicNovuSettings } from "@/hooks/usePublicNovuSettings";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { notificationService } from "@/lib/notificationService";

interface ChannelPreferences {
  in_app: boolean;
  email: boolean;
  push: boolean;
}

interface WorkflowPreferences {
  [workflowId: string]: boolean;
}

interface FrequencySettings {
  digest: 'realtime' | 'hourly' | 'daily' | 'weekly';
  max_per_hour: number;
}

interface NotificationTemplate {
  id: string;
  workflow_id: string;
  name: string;
  description: string;
  category: string;
  is_active: boolean;
}

export function NotificationsTab() {
  const { user } = useAuth();
  const { isEnabled: isNovuEnabled, isLoading: isNovuLoading } = usePublicNovuSettings();
  const [loading, setLoading] = useState(true);
  const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
  const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>({
    in_app: true,
    email: true,
    push: false,
  });
  const [workflowPreferences, setWorkflowPreferences] = useState<WorkflowPreferences>({});
  const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>({
    digest: 'daily',
    max_per_hour: 10,
  });

  useEffect(() => {
    if (user) {
      loadPreferences();
      loadTemplates();
    }
  }, [user]);

  const loadPreferences = async () => {
    if (!user) return;

    try {
      const preferences = await notificationService.getPreferences(user.id);
      
      if (preferences) {
        const { sms, ...channelPrefs } = preferences.channelPreferences;
        setChannelPreferences(channelPrefs);
        setWorkflowPreferences(preferences.workflowPreferences);
        setFrequencySettings(preferences.frequencySettings);
      }
    } catch (error) {
      console.error('Error loading preferences:', error);
      toast.error("Failed to load notification preferences");
    } finally {
      setLoading(false);
    }
  };

  const loadTemplates = async () => {
    try {
      const templateData = await notificationService.getTemplates();
      setTemplates(templateData);
      
      // Initialize workflow preferences if not set
      const initialPrefs: WorkflowPreferences = {};
      templateData.forEach((template) => {
        if (!(template.workflow_id in workflowPreferences)) {
          initialPrefs[template.workflow_id] = true;
        }
      });
      if (Object.keys(initialPrefs).length > 0) {
        setWorkflowPreferences((prev) => ({ ...prev, ...initialPrefs }));
      }
    } catch (error) {
      console.error('Error loading templates:', error);
    }
  };

  const savePreferences = async () => {
    if (!user) return;

    setLoading(true);
    try {
      const result = await notificationService.updatePreferences(user.id, {
        channelPreferences: {
          ...channelPreferences,
          sms: false, // SMS not supported in UI
        },
        workflowPreferences,
        frequencySettings,
      });

      if (result.success) {
        toast.success("Notification preferences saved successfully");
        
        // Also update Novu subscriber profile to sync channel preferences
        if (notificationService.isEnabled()) {
          await notificationService.updateSubscriber({
            subscriberId: user.id,
            email: user.email,
          });
        }
      } else {
        throw new Error(result.error || 'Failed to save preferences');
      }
    } catch (error: any) {
      console.error('Error saving preferences:', error);
      toast.error(error.message || "Failed to save notification preferences");
    } finally {
      setLoading(false);
    }
  };

  const updateChannelPreference = (channel: keyof ChannelPreferences, value: boolean) => {
    setChannelPreferences((prev) => ({ ...prev, [channel]: value }));
  };

  const updateWorkflowPreference = (workflowId: string, value: boolean) => {
    setWorkflowPreferences((prev) => ({ ...prev, [workflowId]: value }));
  };

  const requestPushPermission = async () => {
    if (!('Notification' in window)) {
      toast.error("This browser doesn't support push notifications");
      return;
    }

    try {
      const permission = await Notification.requestPermission();
      if (permission === 'granted') {
        updateChannelPreference('push', true);
        toast.success("Push notifications enabled");
      } else {
        toast.error("Push notification permission denied");
      }
    } catch (error) {
      console.error('Error requesting push permission:', error);
      toast.error("Failed to enable push notifications");
    }
  };

  const groupedTemplates = templates.reduce((acc, template) => {
    if (!acc[template.category]) {
      acc[template.category] = [];
    }
    acc[template.category].push(template);
    return acc;
  }, {} as Record<string, NotificationTemplate[]>);

  return (
    <div className="space-y-6">
      {isNovuLoading ? (
        <Card>
          <CardHeader>
            <CardDescription>Loading notification settings...</CardDescription>
          </CardHeader>
        </Card>
      ) : !isNovuEnabled ? (
        <Card className="border-yellow-500/50 bg-yellow-500/10">
          <CardHeader>
            <CardTitle className="text-yellow-600 dark:text-yellow-400">Novu Not Configured</CardTitle>
            <CardDescription>
              Novu notifications are not configured. Contact an administrator to configure the Novu Application Identifier in admin settings.
            </CardDescription>
          </CardHeader>
        </Card>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>Notification Channels</CardTitle>
          <CardDescription>
            Choose which channels you'd like to receive notifications through
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label className="flex items-center gap-2">
                In-App Notifications
                <Badge variant="secondary" className="text-xs">Real-time</Badge>
              </Label>
              <p className="text-sm text-muted-foreground">
                Receive notifications within the application
              </p>
            </div>
            <Switch
              checked={channelPreferences.in_app}
              onCheckedChange={(checked) => updateChannelPreference('in_app', checked)}
            />
          </div>

          <Separator />

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Email Notifications</Label>
              <p className="text-sm text-muted-foreground">
                Receive notifications via email
              </p>
            </div>
            <Switch
              checked={channelPreferences.email}
              onCheckedChange={(checked) => updateChannelPreference('email', checked)}
            />
          </div>

          <Separator />

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Push Notifications</Label>
              <p className="text-sm text-muted-foreground">
                Browser push notifications
              </p>
            </div>
            <Switch
              checked={channelPreferences.push}
              onCheckedChange={(checked) => {
                if (checked) {
                  requestPushPermission();
                } else {
                  updateChannelPreference('push', false);
                }
              }}
            />
          </div>

        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Notification Frequency</CardTitle>
          <CardDescription>
            Control how often you receive notifications
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Digest Frequency</Label>
            <Select
              value={frequencySettings.digest}
              onValueChange={(value: any) => 
                setFrequencySettings((prev) => ({ ...prev, digest: value }))
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="realtime">Real-time</SelectItem>
                <SelectItem value="hourly">Hourly</SelectItem>
                <SelectItem value="daily">Daily</SelectItem>
                <SelectItem value="weekly">Weekly</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-sm text-muted-foreground">
              Group notifications and send them in batches
            </p>
          </div>

          <Separator />

          <div className="space-y-2">
            <Label>Maximum Notifications Per Hour</Label>
            <Select
              value={frequencySettings.max_per_hour.toString()}
              onValueChange={(value) => 
                setFrequencySettings((prev) => ({ ...prev, max_per_hour: parseInt(value) }))
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="5">5 per hour</SelectItem>
                <SelectItem value="10">10 per hour</SelectItem>
                <SelectItem value="20">20 per hour</SelectItem>
                <SelectItem value="50">50 per hour</SelectItem>
                <SelectItem value="999">Unlimited</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-sm text-muted-foreground">
              Limit the number of notifications you receive per hour
            </p>
          </div>
        </CardContent>
      </Card>

      {Object.keys(groupedTemplates).map((category) => (
        <Card key={category}>
          <CardHeader>
            <CardTitle className="capitalize">{category} Notifications</CardTitle>
            <CardDescription>
              Manage your {category} notification preferences
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {groupedTemplates[category].map((template, index) => (
              <div key={template.id}>
                {index > 0 && <Separator className="my-4" />}
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>{template.name}</Label>
                    <p className="text-sm text-muted-foreground">
                      {template.description}
                    </p>
                  </div>
                  <Switch
                    checked={workflowPreferences[template.workflow_id] ?? true}
                    onCheckedChange={(checked) => 
                      updateWorkflowPreference(template.workflow_id, checked)
                    }
                  />
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      ))}

      <Button 
        onClick={savePreferences}
        className="w-full"
        disabled={loading}
      >
        {loading ? 'Saving...' : 'Save Notification Preferences'}
      </Button>
    </div>
  );
}
