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 { Skeleton } from "@/components/ui/skeleton";
import { handleError, handleSuccess, handleInfo } from "@/lib/errorHandler";
import { logger } from "@/lib/logger";
import { notificationService } from "@/lib/notificationService";
import type {
  NotificationPreferences,
  NotificationTemplate,
  ChannelPreferences,
  WorkflowPreferences,
  FrequencySettings
} from "@/types/notifications";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@/lib/notificationValidation";

export function NotificationsTab() {
  const { user } = useAuth();
  const { isEnabled: isNovuEnabled, isLoading: isNovuLoading } = usePublicNovuSettings();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
  const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>(
    DEFAULT_NOTIFICATION_PREFERENCES.channelPreferences
  );
  const [workflowPreferences, setWorkflowPreferences] = useState<WorkflowPreferences>({});
  const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>(
    DEFAULT_NOTIFICATION_PREFERENCES.frequencySettings
  );

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

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

    try {
      const preferences = await notificationService.getPreferences(user.id);
      
      if (preferences) {
        setChannelPreferences(preferences.channelPreferences);
        setWorkflowPreferences(preferences.workflowPreferences);
        setFrequencySettings(preferences.frequencySettings);
      }

      logger.info('Notification preferences loaded', {
        action: 'load_notification_preferences',
        userId: user.id
      });
    } catch (error: unknown) {
      logger.error('Failed to load notification preferences', {
        action: 'load_notification_preferences',
        userId: user.id,
        error: error instanceof Error ? error.message : String(error)
      });

      handleError(error, {
        action: 'Load notification preferences',
        userId: user.id
      });
    } finally {
      setLoading(false);
    }
  };

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

    try {
      const templateData = await notificationService.getTemplates();
      setTemplates(templateData);
      
      // Initialize workflow preferences for new templates
      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 }));
      }

      logger.info('Notification templates loaded', {
        action: 'load_notification_templates',
        userId: user.id,
        count: templateData.length
      });
    } catch (error: unknown) {
      logger.error('Failed to load notification templates', {
        action: 'load_notification_templates',
        userId: user.id,
        error: error instanceof Error ? error.message : String(error)
      });

      handleError(error, {
        action: 'Load notification templates',
        userId: user.id
      });
    }
  };

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

    setSaving(true);

    try {
      const preferences: NotificationPreferences = {
        channelPreferences,
        workflowPreferences,
        frequencySettings
      };

      const result = await notificationService.updatePreferences(user.id, preferences);

      if (!result.success) {
        throw new Error(result.error || 'Failed to save notification preferences');
      }

      logger.info('Notification preferences saved', {
        action: 'save_notification_preferences',
        userId: user.id
      });

      handleSuccess(
        'Notification preferences saved',
        'Your notification settings have been updated successfully.'
      );
    } catch (error: unknown) {
      logger.error('Error saving notification preferences', {
        action: 'save_notification_preferences',
        userId: user.id,
        error: error instanceof Error ? error.message : String(error)
      });

      handleError(error, {
        action: 'Save notification preferences',
        userId: user.id
      });
    } finally {
      setSaving(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)) {
      handleInfo(
        'Push notifications not supported',
        'Your browser does not support push notifications.'
      );
      return;
    }

    try {
      const permission = await Notification.requestPermission();
      
      if (permission === 'granted') {
        updateChannelPreference('push', true);
        handleSuccess('Push notifications enabled', 'You will now receive push notifications.');
      } else {
        handleInfo(
          'Permission denied',
          'Push notifications were not enabled. You can change this in your browser settings.'
        );
      }
    } catch (error: unknown) {
      logger.error('Error requesting push permission', {
        action: 'request_push_permission',
        userId: user?.id,
        error: error instanceof Error ? error.message : String(error)
      });

      handleError(error, {
        action: 'Enable push notifications',
        userId: user?.id
      });
    }
  };

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

  if (loading || isNovuLoading) {
    return (
      <div className="space-y-6">
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-48" />
            <Skeleton className="h-4 w-full max-w-md" />
          </CardHeader>
          <CardContent className="space-y-4">
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-12 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {!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>
              Notifications are not fully configured. Contact an administrator to enable Novu integration.
            </CardDescription>
          </CardHeader>
        </Card>
      )}

      {/* Notification Channels + Frequency Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Notification Channels */}
        <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>

        {/* Notification Frequency */}
        <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: 'realtime' | 'hourly' | 'daily' | 'weekly') => 
                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>
      </div>

      {/* Workflow Preferences - Full Width */}
      {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>
                    {template.description && (
                      <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={saving}
      >
        {saving ? 'Saving...' : 'Save Notification Preferences'}
      </Button>
    </div>
  );
}
