import { useFetcher } from "react-router";
import { Switch } from "~/components/ui/switch";
import { Label } from "~/components/ui/label";

type Props = {
  discordPingEnabled: boolean;
  hasDiscordLinked: boolean;
  success?: boolean;
  error?: string;
  onNavigateToAccount: () => void;
};

export function NotificationsSection({ discordPingEnabled, hasDiscordLinked, success, error, onNavigateToAccount }: Props) {
  const fetcher = useFetcher();
  const optimisticEnabled =
    fetcher.state !== "idle"
      ? fetcher.formData?.get("discordPingEnabled") === "true"
      : discordPingEnabled;

  const handleToggle = (checked: boolean) => {
    fetcher.submit(
      { intent: "update-discord-ping", discordPingEnabled: String(checked) },
      { method: "post" }
    );
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-lg font-semibold">Notifications</h2>
        <p className="text-sm text-muted-foreground">
          Manage how you receive league notifications.
        </p>
      </div>

      <div className="rounded-lg border p-4 space-y-4">
        <h3 className="text-sm font-medium">Discord Pings</h3>

        {!hasDiscordLinked ? (
          <p className="text-sm text-muted-foreground">
            Link your Discord account in{" "}
            <button
              type="button"
              onClick={onNavigateToAccount}
              className="text-primary underline-offset-4 hover:underline"
            >
              Account settings
            </button>{" "}
            to enable Discord pings for league notifications.
          </p>
        ) : (
          <>
            <div className="flex items-center justify-between gap-4">
              <div className="space-y-1">
                <Label htmlFor="discord-ping-switch" className="text-sm font-normal">
                  Ping me in standings updates
                </Label>
                <p className="text-xs text-muted-foreground">
                  When enabled, you'll be @mentioned in league Discord notifications and your
                  Discord display name will appear in place of your brackt username.
                </p>
              </div>
              <Switch
                id="discord-ping-switch"
                checked={optimisticEnabled}
                onCheckedChange={handleToggle}
                disabled={fetcher.state !== "idle"}
              />
            </div>
            {success && (
              <p className="text-sm text-green-600">Notification preference saved.</p>
            )}
            {error && (
              <p className="text-sm text-destructive">{error}</p>
            )}
          </>
        )}
      </div>
    </div>
  );
}
