import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Switch } from './ui/switch';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { useNotifications } from './NotificationProvider';
import { Bell, BellOff, Shield, CreditCard, Users, Zap, Gift } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface NotificationPreferences {
  transactions: boolean;
  groupSavings: boolean;
  billPayments: boolean;
  security: boolean;
  promotions: boolean;
  reminders: boolean;
}

interface NotificationSettingsProps {
  onBack: () => void;
}

export const NotificationSettings: React.FC<NotificationSettingsProps> = ({ onBack }) => {
  const { permission, isSubscribed, requestPermission } = useNotifications();
  const [preferences, setPreferences] = useState<NotificationPreferences>({
    transactions: true,
    groupSavings: true,
    billPayments: true,
    security: true,
    promotions: false,
    reminders: true
  });
  const [isLoading, setIsLoading] = useState(false);

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

  const loadPreferences = () => {
    const saved = localStorage.getItem('enamel_notification_preferences');
    if (saved) {
      try {
        setPreferences(JSON.parse(saved));
      } catch (error) {
        console.error('Error loading notification preferences:', error);
      }
    }
  };

  const savePreferences = async (newPreferences: NotificationPreferences) => {
    setIsLoading(true);
    try {
      localStorage.setItem('enamel_notification_preferences', JSON.stringify(newPreferences));
      setPreferences(newPreferences);
      toast.success('Notification preferences updated');
    } catch (error) {
      console.error('Error saving preferences:', error);
      toast.error('Failed to save preferences');
    } finally {
      setIsLoading(false);
    }
  };

  const handlePreferenceChange = (key: keyof NotificationPreferences, value: boolean) => {
    const newPreferences = { ...preferences, [key]: value };
    savePreferences(newPreferences);
  };

  const handleEnableNotifications = async () => {
    setIsLoading(true);
    try {
      await requestPermission();
    } finally {
      setIsLoading(false);
    }
  };

  const getPermissionStatus = () => {
    // Check if we're in iframe environment
    const isInIframe = window.self !== window.top;
    const isFigmaPreview = window.location.hostname.includes('figma');
    
    if (isInIframe || isFigmaPreview) {
      return {
        status: 'Visual Notifications',
        description: 'In-app notifications are available (browser notifications not supported in this environment)',
        color: 'bg-blue-500',
        icon: <Bell className="w-4 h-4" />
      };
    }

    if (!('Notification' in window)) {
      return {
        status: 'Not Supported',
        description: 'Your browser doesn\'t support notifications',
        color: 'bg-gray-500',
        icon: <BellOff className="w-4 h-4" />
      };
    }

    switch (permission) {
      case 'granted':
        return {
          status: isSubscribed ? 'Fully Enabled' : 'Basic Enabled',
          description: isSubscribed 
            ? 'Push notifications are active' 
            : 'Basic notifications are active',
          color: 'bg-green-500',
          icon: <Bell className="w-4 h-4" />
        };
      case 'denied':
        return {
          status: 'Blocked',
          description: 'Please enable in browser settings',
          color: 'bg-red-500',
          icon: <BellOff className="w-4 h-4" />
        };
      default:
        return {
          status: 'Disabled',
          description: 'Click to enable notifications',
          color: 'bg-yellow-500',
          icon: <Bell className="w-4 h-4" />
        };
    }
  };

  const permissionInfo = getPermissionStatus();

  const notificationTypes = [
    {
      key: 'transactions' as keyof NotificationPreferences,
      title: 'Transaction Alerts',
      description: 'Get notified when money enters or leaves your wallet',
      icon: <CreditCard className="w-5 h-5 text-blue-600" />,
      important: true
    },
    {
      key: 'security' as keyof NotificationPreferences,
      title: 'Security Alerts',
      description: 'Important security notifications and login alerts',
      icon: <Shield className="w-5 h-5 text-red-600" />,
      important: true
    },
    {
      key: 'groupSavings' as keyof NotificationPreferences,
      title: 'Group Savings',
      description: 'Updates about your group savings and contribution turns',
      icon: <Users className="w-5 h-5 text-green-600" />,
      important: false
    },
    {
      key: 'billPayments' as keyof NotificationPreferences,
      title: 'Bill Payments',
      description: 'Confirmations for utility bills and airtime purchases',
      icon: <Zap className="w-5 h-5 text-orange-600" />,
      important: false
    },
    {
      key: 'reminders' as keyof NotificationPreferences,
      title: 'Savings Reminders',
      description: 'Reminders about your savings goals and maturity dates',
      icon: <Gift className="w-5 h-5 text-purple-600" />,
      important: false
    },
    {
      key: 'promotions' as keyof NotificationPreferences,
      title: 'Promotions & Updates',
      description: 'Special offers, new features, and product updates',
      icon: <Gift className="w-5 h-5 text-pink-600" />,
      important: false
    }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="flex items-center gap-4 mb-6">
          <Button
            variant="ghost"
            size="sm"
            onClick={onBack}
            className="p-2"
          >
            ←
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Notification Settings</h1>
            <p className="text-gray-600">Manage how you receive notifications</p>
          </div>
        </div>

        {/* Permission Status */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-3">
              <Bell className="w-6 h-6 text-blue-600" />
              Push Notifications
            </CardTitle>
            <CardDescription>
              Control when and how you receive push notifications
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Badge className={`${permissionInfo.color} text-white`}>
                  {permissionInfo.icon}
                  <span className="ml-1">{permissionInfo.status}</span>
                </Badge>
                <span className="text-sm text-gray-600">
                  {permissionInfo.description}
                </span>
              </div>
              
              {permission === 'default' && (
                <Button
                  onClick={handleEnableNotifications}
                  disabled={isLoading}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  {isLoading ? 'Enabling...' : 'Enable Notifications'}
                </Button>
              )}
            </div>

            {permission === 'denied' && (
              <div className="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p className="text-sm text-yellow-800">
                  <strong>Notifications are blocked.</strong> To enable them:
                </p>
                <ol className="mt-2 text-sm text-yellow-700 list-decimal list-inside space-y-1">
                  <li>Click the lock icon in your browser's address bar</li>
                  <li>Change notifications from "Block" to "Allow"</li>
                  <li>Refresh this page</li>
                </ol>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Notification Preferences */}
        <Card>
          <CardHeader>
            <CardTitle>Notification Types</CardTitle>
            <CardDescription>
              Choose what notifications you want to receive
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {notificationTypes.map((type) => (
              <div key={type.key} className="flex items-start gap-4">
                <div className="flex-shrink-0 mt-1">
                  {type.icon}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-medium text-gray-900">{type.title}</h3>
                    {type.important && (
                      <Badge variant="secondary" className="text-xs">
                        Recommended
                      </Badge>
                    )}
                  </div>
                  <p className="text-sm text-gray-600">{type.description}</p>
                </div>
                <Switch
                  checked={preferences[type.key]}
                  onCheckedChange={(checked) => handlePreferenceChange(type.key, checked)}
                  disabled={isLoading || permission !== 'granted'}
                />
              </div>
            ))}
          </CardContent>
        </Card>

        {/* Information */}
        <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex gap-3">
            <Bell className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
            <div>
              <h4 className="font-medium text-blue-900 mb-1">About Notifications</h4>
              <p className="text-sm text-blue-700">
                We only send notifications for important account activities and features you've enabled. 
                You can change these settings anytime. Security alerts cannot be disabled for your protection.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};