import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Bell, Mail, MessageSquare, Loader2, CheckCircle, AlertCircle, Settings } from 'lucide-react';
import { getNotificationPreferences, updateNotificationPreferences, NotificationPreferences } from '@/services/userPreferenceApi';
import { Separator } from '@/components/ui/separator';

interface NotificationPreferencesModalProps {
  open: boolean;
  onClose: () => void;
}

export function NotificationPreferencesModal({ open, onClose }: NotificationPreferencesModalProps) {
  const [preferences, setPreferences] = useState<NotificationPreferences>({
    emailNotificationsEnabled: true,
    pushNotificationsEnabled: true,
    inAppNotificationsEnabled: true
  });
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

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

  const loadPreferences = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getNotificationPreferences();
      setPreferences(data);
    } catch (err: any) {
      console.error('[NotificationPreferences] Failed to load preferences:', err);
      setError(err.response?.data?.message || 'Failed to load notification preferences');
    } finally {
      setLoading(false);
    }
  };

  const handleToggle = async (key: keyof NotificationPreferences, value: boolean) => {
    try {
      setUpdating(key);
      setError(null);
      setSuccessMessage(null);

      const updateData = { [key]: value };
      const updated = await updateNotificationPreferences(updateData);
      
      setPreferences(updated);
      
      // Show success message
      const prefName = key === 'emailNotificationsEnabled' ? 'Email' 
        : key === 'pushNotificationsEnabled' ? 'Push' 
        : 'In-App';
      setSuccessMessage(`${prefName} notifications ${value ? 'enabled' : 'disabled'}`);
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err: any) {
      console.error('[NotificationPreferences] Failed to update preference:', err);
      setError(err.response?.data?.message || 'Failed to update notification preference');
      // Revert the UI change
      loadPreferences();
    } finally {
      setUpdating(null);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[600px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg">
              <Settings className="h-6 w-6 text-white" />
            </div>
            <div>
              <DialogTitle className="text-xl font-semibold">Notification Preferences</DialogTitle>
              <DialogDescription className="text-sm">
                Customize how you receive notifications for workflow updates
              </DialogDescription>
            </div>
          </div>
        </DialogHeader>

        <Separator className="my-4" />

        {loading ? (
          <div className="p-12 flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
          </div>
        ) : (
          <div className="space-y-6">
            {/* Success Message */}
            {successMessage && (
              <div className="flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-md animate-in fade-in slide-in-from-top-2">
                <CheckCircle className="w-4 h-4 text-green-600 shrink-0" />
                <p className="text-sm text-green-800 font-medium">{successMessage}</p>
              </div>
            )}

            {/* Error Message */}
            {error && (
              <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2">
                <AlertCircle className="w-4 h-4 text-red-600 shrink-0" />
                <p className="text-sm text-red-800 font-medium">{error}</p>
              </div>
            )}

            {/* Email Notifications */}
            <div className="space-y-2">
              <div className="flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-white rounded-lg shadow-sm">
                    <Mail className="w-6 h-6 text-slate-600" />
                  </div>
                  <div>
                    <Label htmlFor="email-notifications-modal" className="text-base font-semibold text-gray-900 cursor-pointer">
                      Email Notifications
                    </Label>
                    <p className="text-sm text-gray-600 mt-1">
                      Receive important updates and alerts via email
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {updating === 'emailNotificationsEnabled' && (
                    <Loader2 className="w-4 h-4 animate-spin text-gray-400" />
                  )}
                  <Switch
                    id="email-notifications-modal"
                    checked={preferences.emailNotificationsEnabled}
                    onCheckedChange={(checked) => handleToggle('emailNotificationsEnabled', checked)}
                    disabled={updating === 'emailNotificationsEnabled'}
                  />
                </div>
              </div>
            </div>

            {/* Push Notifications */}
            <div className="space-y-2">
              <div className="flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-white rounded-lg shadow-sm">
                    <Bell className="w-6 h-6 text-slate-600" />
                  </div>
                  <div>
                    <Label htmlFor="push-notifications-modal" className="text-base font-semibold text-gray-900 cursor-pointer">
                      Push Notifications
                    </Label>
                    <p className="text-sm text-gray-600 mt-1">
                      Get instant browser notifications for real-time updates
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {updating === 'pushNotificationsEnabled' && (
                    <Loader2 className="w-4 h-4 animate-spin text-gray-400" />
                  )}
                  <Switch
                    id="push-notifications-modal"
                    checked={preferences.pushNotificationsEnabled}
                    onCheckedChange={(checked) => handleToggle('pushNotificationsEnabled', checked)}
                    disabled={updating === 'pushNotificationsEnabled'}
                  />
                </div>
              </div>
            </div>

            {/* In-App Notifications */}
            <div className="space-y-2">
              <div className="flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-white rounded-lg shadow-sm">
                    <MessageSquare className="w-6 h-6 text-slate-600" />
                  </div>
                  <div>
                    <Label htmlFor="inapp-notifications-modal" className="text-base font-semibold text-gray-900 cursor-pointer">
                      In-App Notifications
                    </Label>
                    <p className="text-sm text-gray-600 mt-1">
                      View notifications in the notification center
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {updating === 'inAppNotificationsEnabled' && (
                    <Loader2 className="w-4 h-4 animate-spin text-gray-400" />
                  )}
                  <Switch
                    id="inapp-notifications-modal"
                    checked={preferences.inAppNotificationsEnabled}
                    onCheckedChange={(checked) => handleToggle('inAppNotificationsEnabled', checked)}
                    disabled={updating === 'inAppNotificationsEnabled'}
                  />
                </div>
              </div>
            </div>

            <Separator />

            {/* Info Section */}
            <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
              <p className="text-sm text-gray-700 leading-relaxed">
                <span className="font-semibold">Note:</span> These settings control your notification preferences across all channels. 
                Critical system alerts and urgent notifications may still be delivered regardless of these settings to ensure important information reaches you.
              </p>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

