import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Bell, Mail, Save, Loader2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import {
  type NotificationCategory,
  NOTIFICATION_CATEGORY_LABELS,
  NOTIFICATION_CATEGORY_DESCRIPTIONS,
  DEFAULT_NOTIFICATION_PREFERENCES,
} from "@/lib/notificationPreferences";

interface Props {
  userId: string;
  initialPreferences?: Record<string, boolean> | null;
  initialPreferredEmail?: string | null;
}

const CATEGORIES: NotificationCategory[] = [
  "messages_comments",
  "financial",
  "governance",
  "compliance",
];

export default function NotificationPreferencesCard({
  userId,
  initialPreferences,
  initialPreferredEmail,
}: Props) {
  const [prefs, setPrefs] = useState<Record<NotificationCategory, boolean>>(
    DEFAULT_NOTIFICATION_PREFERENCES
  );
  const [preferredEmail, setPreferredEmail] = useState<string>("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (initialPreferences) {
      setPrefs({
        messages_comments: initialPreferences.messages_comments !== false,
        financial: initialPreferences.financial !== false,
        governance: initialPreferences.governance !== false,
        compliance: initialPreferences.compliance !== false,
      });
    }
    setPreferredEmail(initialPreferredEmail || "");
  }, [initialPreferences, initialPreferredEmail]);

  const toggle = (cat: NotificationCategory) =>
    setPrefs((p) => ({ ...p, [cat]: !p[cat] }));

  const handleSave = async () => {
    if (!userId) return;
    setSaving(true);
    const { error } = await supabase
      .from("profiles")
      .update({
        notification_preferences: prefs,
        preferred_notification_email: preferredEmail.trim() || null,
      })
      .eq("user_id", userId);
    setSaving(false);
    if (error) toast.error("Failed to save preferences");
    else toast.success("Notification preferences saved");
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <Bell className="h-5 w-5 text-primary" /> Email Notifications
        </CardTitle>
        <CardDescription>
          Choose which categories you want to receive email notifications about.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        <div className="space-y-2">
          <Label htmlFor="pref-email">Send notifications to</Label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              id="pref-email"
              type="email"
              value={preferredEmail}
              onChange={(e) => setPreferredEmail(e.target.value)}
              className="pl-9"
              placeholder="Leave blank to use your account email"
            />
          </div>
          <p className="text-xs text-muted-foreground">
            Optional alternate email for notifications only.
          </p>
        </div>

        <Separator />

        <div className="space-y-4">
          {CATEGORIES.map((cat) => (
            <div
              key={cat}
              className="flex items-start justify-between gap-4 rounded-md border bg-card p-4"
            >
              <div className="flex-1">
                <p className="text-sm font-medium text-foreground">
                  {NOTIFICATION_CATEGORY_LABELS[cat]}
                </p>
                <p className="text-xs text-muted-foreground mt-0.5">
                  {NOTIFICATION_CATEGORY_DESCRIPTIONS[cat]}
                </p>
              </div>
              <Switch
                checked={prefs[cat]}
                onCheckedChange={() => toggle(cat)}
                aria-label={`Toggle ${NOTIFICATION_CATEGORY_LABELS[cat]}`}
              />
            </div>
          ))}
        </div>

        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving} className="gap-2">
            {saving ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            {saving ? "Saving…" : "Save Preferences"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
