import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Bell, Mail, Calendar, Briefcase, AlertCircle, CheckCircle } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { Badge } from "@/components/ui/badge";

export default function NotificationSettings() {
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: currentUser } = useQuery({
    queryKey: ['current-user-notification-settings'],
    queryFn: () => base44.auth.me(),
  });

  const [preferences, setPreferences] = useState(
    currentUser?.notification_preferences || {
      email_notifications: true,
      in_app_notifications: true,
      shift_assignments: true,
      shift_reminders: true,
      shift_changes: true,
      upcoming_events: true,
      new_leads: true,
      invoice_updates: true,
      system_alerts: true,
    }
  );

  const updatePreferencesMutation = useMutation({
    mutationFn: (prefs) => base44.auth.updateMe({ notification_preferences: prefs }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-user-notification-settings'] });
      toast({
        title: "✅ Settings Updated",
        description: "Your notification preferences have been saved",
      });
    },
    onError: (error) => {
      toast({
        title: "❌ Update Failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleToggle = (key) => {
    setPreferences(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const handleSave = () => {
    updatePreferencesMutation.mutate(preferences);
  };

  const userRole = currentUser?.role || currentUser?.user_role || 'admin';

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-slate-900">Notification Settings</h1>
          <p className="text-sm text-slate-500 mt-1">
            Configure how and when you receive notifications
          </p>
        </div>

        <div className="space-y-4">
          {/* Global Settings */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Bell className="w-5 h-5" />
                Global Notification Settings
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                <div className="flex items-center gap-3">
                  <Bell className="w-5 h-5 text-blue-600" />
                  <div>
                    <Label className="font-semibold">In-App Notifications</Label>
                    <p className="text-sm text-slate-500">Receive notifications in the app</p>
                  </div>
                </div>
                <Switch
                  checked={preferences.in_app_notifications}
                  onCheckedChange={() => handleToggle('in_app_notifications')}
                />
              </div>

              <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                <div className="flex items-center gap-3">
                  <Mail className="w-5 h-5 text-purple-600" />
                  <div>
                    <Label className="font-semibold">Email Notifications</Label>
                    <p className="text-sm text-slate-500">Receive notifications via email</p>
                  </div>
                </div>
                <Switch
                  checked={preferences.email_notifications}
                  onCheckedChange={() => handleToggle('email_notifications')}
                />
              </div>
            </CardContent>
          </Card>

          {/* Staff/Workforce Notifications */}
          {(userRole === 'workforce' || userRole === 'admin' || userRole === 'vendor') && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Calendar className="w-5 h-5" />
                  Shift Notifications
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Shift Assignments</Label>
                    <p className="text-sm text-slate-500">When you're assigned to a new shift</p>
                  </div>
                  <Switch
                    checked={preferences.shift_assignments}
                    onCheckedChange={() => handleToggle('shift_assignments')}
                  />
                </div>

                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Shift Reminders</Label>
                    <p className="text-sm text-slate-500">24 hours before your shift starts</p>
                  </div>
                  <Switch
                    checked={preferences.shift_reminders}
                    onCheckedChange={() => handleToggle('shift_reminders')}
                  />
                </div>

                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Shift Changes</Label>
                    <p className="text-sm text-slate-500">When shift details are modified</p>
                  </div>
                  <Switch
                    checked={preferences.shift_changes}
                    onCheckedChange={() => handleToggle('shift_changes')}
                  />
                </div>
              </CardContent>
            </Card>
          )}

          {/* Client Notifications */}
          {(userRole === 'client' || userRole === 'admin') && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Briefcase className="w-5 h-5" />
                  Event Notifications
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Upcoming Events</Label>
                    <p className="text-sm text-slate-500">Reminders 3 days before your event</p>
                  </div>
                  <Switch
                    checked={preferences.upcoming_events}
                    onCheckedChange={() => handleToggle('upcoming_events')}
                  />
                </div>

                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Staff Updates</Label>
                    <p className="text-sm text-slate-500">When staff are assigned or changed</p>
                  </div>
                  <Switch
                    checked={preferences.shift_changes}
                    onCheckedChange={() => handleToggle('shift_changes')}
                  />
                </div>
              </CardContent>
            </Card>
          )}

          {/* Vendor Notifications */}
          {(userRole === 'vendor' || userRole === 'admin') && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Briefcase className="w-5 h-5" />
                  Business Notifications
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">New Leads</Label>
                    <p className="text-sm text-slate-500">When new staffing opportunities are available</p>
                  </div>
                  <Switch
                    checked={preferences.new_leads}
                    onCheckedChange={() => handleToggle('new_leads')}
                  />
                </div>

                <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                  <div>
                    <Label className="font-semibold">Invoice Updates</Label>
                    <p className="text-sm text-slate-500">Invoice status changes and payments</p>
                  </div>
                  <Switch
                    checked={preferences.invoice_updates}
                    onCheckedChange={() => handleToggle('invoice_updates')}
                  />
                </div>
              </CardContent>
            </Card>
          )}

          {/* System Notifications */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <AlertCircle className="w-5 h-5" />
                System Notifications
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between p-3 hover:bg-slate-50 rounded-lg">
                <div>
                  <Label className="font-semibold">System Alerts</Label>
                  <p className="text-sm text-slate-500">Important platform updates and announcements</p>
                </div>
                <Switch
                  checked={preferences.system_alerts}
                  onCheckedChange={() => handleToggle('system_alerts')}
                />
              </div>
            </CardContent>
          </Card>

          {/* Save Button */}
          <div className="flex justify-end gap-3">
            <Button
              variant="outline"
              onClick={() => setPreferences(currentUser?.notification_preferences || {})}
            >
              Reset
            </Button>
            <Button
              onClick={handleSave}
              disabled={updatePreferencesMutation.isPending}
              className="bg-[#0A39DF]"
            >
              {updatePreferencesMutation.isPending ? "Saving..." : "Save Preferences"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}